package com.project8.main;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Timer;
import android.webkit.JsResult;

import com.project8.book.Book;
import com.project8.book.Bookmark;
import com.project8.book.Chapter;
import com.project8.book.Figure;
import com.project8.book.Notebook;
import com.project8.book.NotebookPage;
import com.project8.book.Page;
import com.project8.book.StyleChanger;
import com.project8.book.FileRead;
import com.project8.book.TableOfBookmarks;
import com.project8.book.notebookFileStuff;
import com.project8.main.R;
import com.project8.main.Search;

import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings.SettingNotFoundException;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.ViewFlipper;
import android.webkit.WebSettings;

public class Main extends ActivityGroup implements OnTouchListener, OnLongClickListener, SurfaceHolder.Callback, Runnable
{
	//********Russell Variables
	int ndMode = 0;
	int newload = 0;
	
	//Default font when opening the book!!!!
	String fontSize = "24";
	int iMode;
	int ifontSize = 24;
	int iLastPage = 1;
	
	String fontFont = "Arial";
	String fontType = "Normal";
	String fontSrc = "src: url(\"../assets/fonts/ARIAL.ttf\")";
	
	private static int menpos = Menu.FIRST;
	int BOOK_MENU_ITEM = 0;
	int CHAP_MENU_ITEM = 0;
	int PAGE_MENU_ITEM = 0;
	private static final int CHAPTER = 0;
	private static final int PAGES = 1;
	private static final int BOOKMARKS = 2;
	//*******
	final Main main = this;
	
	/* Variables used for layout when orientation is changed */
	final int HORIZONTAL = 0;
	final int VERTICAL = 1;
	
	/* Variables for X and Y coordinates onTouch */
	double downX;
	double downY;
	double upX;
	double upY;
	double initialZoom;
	

		
	String myContentString = null;
	
	//XML Variables 
	ImageButton notesButton;
	ImageButton sizeUpButton;
	ImageButton sizeDownButton;
	ImageButton nightDayButton;
	ImageButton bookmarkButton;
	ImageButton stickyNotesButton;	
	ImageButton searchButton;
	ImageButton toggleButton;
	ImageButton tocButton;
	ImageButton highlighterButton;
	Button closeButton;
	EditText searchBar;
	SeekBar brightnessBar;
	SeekBar progBar;
	PageProgressBar progressBar;	//Logical handling of progressBar. External class which handles listners.
	Toast pageProg;
	TextView progressText;
	LinearLayout notesView;
	LinearLayout bookView;
	LinearLayout toolbarView;
	LinearLayout globalView;
	LinearLayout containerView;
	RelativeLayout bookNavToolView;
	RelativeLayout progressView;
	WebView bookContent;
	WebView bookOverlay;
	EditText notesContent;
	ClipboardManager clipboard;
	String newBook = "";
	Context appContext = this;

	int currXScroll;
	int currYScroll;
	int lastXScroll;
	int lastYScroll;
	
	AbsoluteLayout absoluteBookLayout;
	
	/* State variables used for orientation change */
	boolean day = true;					//Is book currently in Day mode?  True if yes.
	int orientation;
	int areNotesVisible = View.GONE;
	double bookTextSize;
	String textBookContent;
	//CharSequence noteBookContent;
	
	TableOfBookmarks tob;// = new TableOfBookmarks();	//Used ONLY for TESTING Bookmarks
	
	Book book;										//Used ONLY for TESTING Book
	
	
	/* Eventually, these buttons will be removed and their functionality will be replaced by dragging a finger across the screen */
	Button turnRightButton;							//Turn to Next Page
	Button turnLeftButton;							//Turn to Previous Page
	boolean rightButtonIsClickable;
	boolean leftButtonIsClickable;
	long startTime;									//Time when user touches a button -- Used for LongPress functionalitystartTime
	long endTime;									//Time when user stops touching a button -- Used for LongPress functionalitystartTime
	
	/* Glossary Variables */
	boolean shouldShowGlossary = false;
	/**/
	
	
	/*Variable to determine if the Toolbar was open*/
	boolean toolbarOpen = false;
	
	boolean brightnessBarIsVisible = false;
	
	/* ProgressBar Toast information */
	int toastOffsetX;
	int toastOffsetY;
	int screenHeightInPixels;
	int screenWidthInPixels;
	double scrollLength;
	double touchStart;
	double touchEnd;
	/**/
	
	long currentPageNum;							//Page in Book currently displayed
	float downXValue;								//X Co-ordinate where user presses his finger down -- Used in page turning
	Dialog stickyNote;								//The sticky Note pop-up GUI
	Button placeButton;								//Sticky Note Button
	Button cancelButton;							//Sticky Note Button
	boolean pendingSticky = false;					//A Sticky Note is pending if the placeButton has been clicked.
	StickyNote oneSticky;	
	ArrayList<ImageView> displayedStickies = new ArrayList<ImageView>();
	boolean stickyIsShowing = false;		//Determines if you've selected a sticky Note on the current page.  Used to prevent other motion even
	Search searchForString;
	boolean isSearchBarVisible = false;
	
	Bundle bun = new Bundle();
	int bookID = 0;
	
	Page previousPage = null;				//Tracks which page you were on before a call to jumpToPage().  Not always needed.
	
	/* Variables for ImageViewer */
	boolean displayingImageFullScreen = false;
	double finger1X, finger1Y;
	double finger2X, finger2Y;
	int numFingersPressed = 0;
	WebView imageViewer;
	String imageOnDisplay;
	/**/
	
	Thread flinger;
	Thread longPressPageTurn;
			
	/* External Browser */
	WebView browser;
	EditText addressBar;
	boolean displayingExternalPage;
	Button webForward;
	Button webBack;
	Button webRefresh;
	Button webGo;
	ProgressBar webLoading;
	/**/
	
	/* Book Navigation Info (Page Num & Chapter Info at top of page */
	TextView chapterNavDisplay;
	TextView pageNavDisplay;
	/**/
	
	/* Notebook Tabs variables */
	ImageButton closeNotebook;
	RelativeLayout tabLayout;
	LinearLayout tabLayout2;
	HorizontalScrollView tabScrollview;
	Tabs tab;
	
	Notebook theNotebook;
	ArrayList<TextView> allNBTabs;
	TextView currentTab;
	int numberOfTabs;
	int currentTabNum;
	NotebookPage currentNBPage;
	NotebookTabTouch notebookTabTouch;
	boolean firstPress = true;
	double downTime;
	/**/
	
	//Gesture Detector
	GestureDetector mGestureDetector;
	
	/* Used to load page at specific HTML anchors */
	boolean okayToAnchor = false;
	/**/
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);	
		
		brightnessBar = (SeekBar)findViewById(R.id.brightnessBar);
		BrightnessSettings bright = new BrightnessSettings(this, brightnessBar, getWindow(), getContentResolver());
		
		notesButton = (ImageButton) findViewById(R.id.notebookbutton); //id given in the xml
		sizeUpButton = (ImageButton) findViewById(R.id.biggerTextButton); //id given in the xml
		sizeDownButton = (ImageButton) findViewById(R.id.smallerTextButton); //id given in the xml
		tocButton = (ImageButton) findViewById(R.id.tableOfContentsButton); //id given in the xml
		nightDayButton = (ImageButton) findViewById(R.id.nightDay); //id given in the xml
		bookmarkButton = (ImageButton) findViewById(R.id.bookmarkButton); //id given in the xml
		searchButton = (ImageButton) findViewById(R.id.searchButton);
		stickyNotesButton = (ImageButton) findViewById(R.id.stickyNoteButton); //id given in the xml;
		toggleButton = (ImageButton) findViewById(R.id.toggle);
		closeButton = (Button) findViewById(R.id.closeSearchButton);
		notesView = (LinearLayout) findViewById(R.id.viewnotes); //id of notesview in xml
		bookView = (LinearLayout) findViewById(R.id.viewmain);
		containerView = (LinearLayout) findViewById(R.id.container);
		toolbarView = (LinearLayout) findViewById(R.id.toolbar);
		globalView = (LinearLayout) findViewById(R.id.viewhome);
		bookNavToolView = (RelativeLayout) findViewById(R.id.bookNav);
		progressView = (RelativeLayout) findViewById(R.id.progressview);
		bookContent = (WebView) findViewById(R.id.booktext);
		bookOverlay = (WebView) findViewById(R.id.bookOverlay);
		absoluteBookLayout = (AbsoluteLayout)findViewById(R.id.absoluteBook);
		notesContent = (EditText) findViewById(R.id.notebook);
		searchBar = (EditText) findViewById(R.id.search);
		textBookContent = bookContent.getUrl();
		//noteBookContent = notesContent.getText();
		turnRightButton = (Button) findViewById(R.id.pageRightButton); //id given in the xml;
		turnLeftButton = (Button) findViewById(R.id.pageLeftButton); //id given in the xml;		
		
		
		/* Set the margin of the Toolbar using FrameLayout Params */
		FrameLayout test = (FrameLayout) findViewById(R.id.framelayout);
		FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
		FrameLayout.LayoutParams.WRAP_CONTENT,
		FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.NO_GRAVITY);		
		layoutParams.setMargins(0, getDensityPixels(48), 0, 0);
		toolbarView.setLayoutParams(layoutParams);
		
		highlighterButton = (ImageButton) findViewById(R.id.highlightButton);
		highlighterButton.setVisibility(View.VISIBLE);
		highlighterButton.setOnTouchListener(this);

		
		
		//*******
		bookNavToolView.setVisibility(View.GONE);
		//progressView.setVisibility(View.INVISIBLE);
		bookContent.getSettings().setLightTouchEnabled(true);
		bookContent.getSettings().setJavaScriptEnabled(true);
		WebSettings settings = bookContent.getSettings(); 
		settings.setJavaScriptEnabled(true); 
		settings.setPluginsEnabled(true); 
		bookContent.getSettings().setUseWideViewPort(true);		   //Double-Tap .. Zoom in like an image, don't just change text size
		bookContent.getSettings().setLoadWithOverviewMode(true);
		bookContent.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL); 
		bookContent.setInitialScale(1);//Fit content to screen
		
		
		bookContent.setOnTouchListener(new OnTouchListener()
		{
			private int ScrollX1;
			private int ScrollX2;
			private int ScrollY1;
			private int ScrollY2;
			
			public boolean onTouch(View v, MotionEvent evt) 
			{				
				if (evt.getAction() == MotionEvent.ACTION_DOWN ||
			            evt.getAction() == MotionEvent.ACTION_POINTER_DOWN ||
			            evt.getAction() == MotionEvent.ACTION_POINTER_1_DOWN ||
			            evt.getAction() == MotionEvent.ACTION_POINTER_2_DOWN ||
			            evt.getAction() == MotionEvent.ACTION_POINTER_3_DOWN) 
				{
				
						initialZoom = bookContent.getScale();
			            
						if(evt.getPointerCount() >= 3)
						{
							;
						}
						else if (evt.getPointerCount() > 1 && evt.getPointerCount() < 3) 
						{
							System.out.println("Two Fingers touching Book Content");
							
			            	bookContent.getSettings().setBuiltInZoomControls(true);
			                bookContent.getSettings().setSupportZoom(true);
			            }
						else
						{		                
							lastTouchX = evt.getX(); 
					        lastTouchY = evt.getY();
					        downXValue = evt.getX();
					        downTime = evt.getEventTime();
					        hasMoved = false;
					        ScrollX1 = bookContent.getScrollX();
					        ScrollY1 = bookContent.getScrollY();
					        
					        System.out.println("CurrentScrollPos = " + ScrollX1);
					        System.out.println("CurrentScale = " + initialZoom);
				 		}
				 }

			     if(evt.getAction() == MotionEvent.ACTION_MOVE)
			     {
			    	 if(evt.getPointerCount() >= 3)
					 {
						;
					 }
					 else if (evt.getPointerCount() > 1 && evt.getPointerCount() < 3)
			    	 {
			    		 ScrollX2 = bookContent.getScrollX();
			    		 ScrollY2 = bookContent.getScrollY();
			    		 		    		 			    		 
			    		 float currentZoom = bookContent.getScale();
			    		 			    		 			    		 
			    		 if(currentZoom != initialZoom)
			    		 {			    			 
			    			 if(book.getCurrentPage().hasStickyNotes())
			    			 {
			    				 ArrayList<StickyNote> allStickies = book.getCurrentPage().getAllStickyNotes();
			    				 
			    				 for(int stick = 0; stick < allStickies.size(); stick++)
			    				 {
		    						 int newScrollX = (int)((book.getCurrentPage().getAllStickyNotes().get(stick).getXCoordinate()*currentZoom/initialZoom - book.getCurrentPage().getAllStickyNotes().get(stick).getXCoordinate()) + (ScrollX1 * currentZoom/initialZoom) - ScrollX2);
				    				 int newScrollY = (int)((book.getCurrentPage().getAllStickyNotes().get(stick).getYCoordinate()*currentZoom/initialZoom - book.getCurrentPage().getAllStickyNotes().get(stick).getYCoordinate()) + (ScrollY1 * currentZoom/initialZoom) - ScrollY2);		    				 
			    				 
				    				 redrawSingleStickyNote(stick, newScrollX, newScrollY);
			    				 }
			    			 }
			    		 }
			    	 }
			    	 else
			    	 {
			    		 hasMoved = moved(evt); 
			    		 			         
			    		 ScrollX2 = bookContent.getScrollX();
			    		 ScrollY2 = bookContent.getScrollY();
			         
			    		 if(ScrollX2 != ScrollX1 || ScrollY2 != ScrollY1)
			    		 {
			    			 if(book.getCurrentPage().hasStickyNotes())
			    			 {
			    				 redrawStickyNotes(ScrollX1 - ScrollX2, ScrollY1 - ScrollY2);
			    			 }
			    		 }
			    	 }
			     }
			     
			     if (evt.getAction() == MotionEvent.ACTION_UP ||
				            evt.getAction() == MotionEvent.ACTION_POINTER_UP ||
				            evt.getAction() == MotionEvent.ACTION_POINTER_1_UP ||
				            evt.getAction() == MotionEvent.ACTION_POINTER_2_UP ||
				            evt.getAction() == MotionEvent.ACTION_POINTER_3_UP)
			     {
			    	   
			    	 bookContent.getSettings().setBuiltInZoomControls(false);
		             bookContent.getSettings().setSupportZoom(false);
			        
		             float currentX = evt.getX();
			         long currentTime = evt.getEventTime();
			         float difference = Math.abs(downXValue - currentX);
			         long time = currentTime - downTime;
			         ScrollX2 = bookContent.getScrollX();
			         ScrollY2 = bookContent.getScrollY();
			           
			         float currentZoom = bookContent.getScale();
			           
			         if(evt.getPointerCount() >= 1)
			         {    		  
			        	 System.out.println("Both fingers lifted");
			        	   
			        	 if(currentZoom != initialZoom)
			        	 {		        	   
			        		 if(book.getCurrentPage().hasStickyNotes())
			        		 {
			        			 ArrayList<StickyNote> allStickies = book.getCurrentPage().getAllStickyNotes();
			        			 for(int s = 0; s < allStickies.size(); s++)
			        			 {
			        				 StickyNote sNote = allStickies.get(s);
				    					 
			        				 int newScrollX = (int)((sNote.getXCoordinate()*currentZoom/initialZoom - sNote.getXCoordinate()) + (ScrollX1 * currentZoom/initialZoom) - ScrollX2);
			        				 int newScrollY = (int)((book.getCurrentPage().getAllStickyNotes().get(s).getYCoordinate()*currentZoom/initialZoom - book.getCurrentPage().getAllStickyNotes().get(s).getYCoordinate()) + (ScrollY1 * currentZoom/initialZoom) - ScrollY2);
				    				 					    				 
			        				 sNote.setCoordinates((float)(sNote.getXCoordinate() + newScrollX), (float)(sNote.getYCoordinate() + newScrollY));
			        			 }
				    				 
			        			 redrawStickyNotes(0,0);
			        		 }
				    			 
			        		 ScrollX1 = bookContent.getScrollX();
			        		 ScrollY1 = bookContent.getScrollY();
			        	 }
				    }
				    else
				    {
			    		 hasMoved = moved(evt); 
			    		 
			    		 System.out.println("Only one finger lifted");
			    		 
			    		 flinger = new Thread(main);
			    		 flinger.start();
			         			         
			    		 if(ScrollX2 != ScrollX1 || ScrollY2 != ScrollY1)
			    		 {
			    			 if(book.getCurrentPage().hasStickyNotes())
			    			 {
			    				 ArrayList<StickyNote> allStickies = book.getCurrentPage().getAllStickyNotes();
			    				 for(int s = 0; s < allStickies.size(); s++)
			    				 {
			    					 StickyNote sNote = allStickies.get(s);
			    				 
			    					 sNote.setCoordinates((float)((sNote.getXCoordinate() + ScrollX1 - ScrollX2)), (float)((sNote.getYCoordinate() + ScrollY1 - ScrollY2)));
			    				 }
			    				 
			    				 redrawStickyNotes(0,0);
			    			 }
			    		 }
			    	}
		           

			        Log.i("Touch Event:",  "Distance: " + difference + "px Time: " + time + "ms");
		           	 
		            if(ScrollX1 == ScrollX2 && ScrollY1 == ScrollY2 && (time < 150) && (difference < 30))
		            {	            	 
		            	if(!book.getPageName().contains("Quiz") && !book.getPageName().contains("quiz"))
		            	{
		            		if(bookNavToolView.getVisibility() == View.GONE)
			            	{
			            		 bookNavToolView.setVisibility(View.VISIBLE);
				            	 progressView.setVisibility(View.VISIBLE);
				            	 
				            	 if(toolbarOpen)
				            	     toolbarView.setVisibility(View.VISIBLE);
				            	 
				            }
			            	else
			            	{
			            		 bookNavToolView.setVisibility(View.GONE);
				            	 progressView.setVisibility(View.INVISIBLE);
				            	 toolbarView.setVisibility(View.GONE);
				            	 hideBrightnessBar();
			            	}
		            	}
		            }
		           
			        if ( (downXValue < currentX) && (time < 400) && (difference > 100) && bookContent.getScrollX() == 0 && currentPageNum != 1) 
			        {
			               turnPage(turnLeftButton);
			        }

		            if ( (downXValue > currentX) && (time < 400) && (difference > 100) && ScrollX1 == ScrollX2 && currentPageNum != book.numPages() ) 
		            {
		                   turnPage(turnRightButton);
	                }
		             
		         } 		     		
		     	
		         return false;
				}
				
				 float downXValue;
				 long downTime;
			     private float lastTouchX, lastTouchY; 
			     private boolean hasMoved = false; 
			     private boolean moved(MotionEvent evt) { 
			     return hasMoved || Math.abs(evt.getX() - lastTouchX) > 10.0 || Math.abs(evt.getY() - lastTouchY) > 10.0; 
			 }
				
		});
		
		//GestureDetector.OnGestureListener gesture
		
		bun = getIntent().getExtras();
		//book = (Book) bun.get("Book");
		book = Global.books.get(bun.getInt("bookIndex"));
		
		ArrayList<Page> allPagesInThisBook = book.getPages();
		for(Page p : allPagesInThisBook)
		{
			System.out.println("Page NAME: " + p.getPageName());
			System.out.println("Page NUM: " + p.getPageNum());
		}
		
		/* Notebook Tab Initialization */
		closeNotebook = (ImageButton) findViewById(R.id.closeNotebook);
		tabLayout = (RelativeLayout) findViewById(R.id.tablayout);
		tabLayout2 = (LinearLayout) findViewById(R.id.tablayout2);
		tabScrollview = (HorizontalScrollView) findViewById(R.id.scrolltabs);
		tab = new Tabs(tabLayout, tabLayout2, tabScrollview, closeNotebook, notesView);
		theNotebook = book.getNotebook();
		notebookTabTouch = new NotebookTabTouch(this);
		allNBTabs = new ArrayList<TextView>();
				
		if(theNotebook.getNumNotebookPages() == 0)
		{
			NotebookPage firstPage = new NotebookPage();
			firstPage.setTabLabel("Notes");
			
			theNotebook.addNewNBPage(firstPage);
		}
		
		numberOfTabs = theNotebook.getNumNotebookPages();
				
		for(int tab = 0; tab < theNotebook.getNumNotebookPages(); tab++)
		{
			TextView newtab = new TextView(this);
			LinearLayout.LayoutParams layoutP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			layoutP.setMargins(3,0,0,0);
			newtab.setPadding(10,5,10,5);
			newtab.setLayoutParams(layoutP);
			newtab.setText(theNotebook.getNBPage(tab).getTabLabel());
									
			if(tab == theNotebook.getNumNotebookPages() - 1)
			{
				newtab.setBackgroundColor(Color.parseColor("#FFCC0000"));
				newtab.setTextColor(Color.parseColor("#FFFFFFFF"));
				newtab.setTextSize(18);
				
				/* Set appropriate content in Notebook, and place cursor at end of last note. */
				notesContent.setText(theNotebook.getNBPage(tab).getTextOnPage());
				Editable notes = main.notesContent.getText(); 
				int position = notes.length(); 
				Selection.setSelection(notes, position); 

				
				currentTab = newtab;
				currentTabNum = tab;
				currentNBPage = theNotebook.getNBPage(tab);
			}
			else
			{
				newtab.setBackgroundColor(Color.parseColor("#FF980000"));
				newtab.setTextColor(Color.parseColor("#FFCCCCCC"));
				newtab.setTextSize(14);
			}
			
			notebookTabTouch.initializeTabSettings(newtab);
			
			tabLayout2.addView(newtab);
			
			TextView addTabButton = new TextView(this);
			LinearLayout.LayoutParams addTabLayout = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			addTabLayout.setMargins(3,5,0,0);
			addTabButton.setPadding(10,0,10,0);
			addTabButton.setBackgroundColor(Color.parseColor("#FF980000"));
			addTabButton.setTextColor(Color.parseColor("#FFFFFFFF"));
			addTabButton.setLayoutParams(addTabLayout);
			addTabButton.setTextSize(20);
			addTabButton.setTypeface(Typeface.DEFAULT_BOLD);
			addTabButton.setText("+");
			addTabButton.setOnClickListener(new OnClickListener(){

				public void onClick(View v) {
					
					System.out.println("Child Count:" + tabLayout2.getChildCount());
					tabLayout2.removeViewAt(tabLayout2.getChildCount() - 1);
					
					addNotebookTab();
					
					tabLayout2.addView(v);
					
					
				}
				
			});
			
			
			tabLayout2.addView(addTabButton);
			allNBTabs.add(newtab);
				
		}
		/**/
			
		tob = book.getTableOfBookmarks();
		book.setCurrentPage(book.getPages().get(0));
		bookContent.loadUrl(book.getPages().get(0).getPageContent());		//Set first View to first Page             
		currentPageNum = book.getPages().get(0).getPageNum();				//We may need to consider pages with Roman Numerals and Letters in their Page Numbers
				
		turnLeftButton.setClickable(false);
		turnLeftButton.setLongClickable(false);
		turnLeftButton.setTextColor(Color.parseColor("Red"));				//Simply indicates you can't go to previous Page
		turnLeftButton.setVisibility(View.INVISIBLE);
		rightButtonIsClickable = true;
		leftButtonIsClickable = false;
		
		bookView.setOnTouchListener((OnTouchListener) this);				//Touch Listener for TextBook pages
		bookOverlay.setOnTouchListener((OnTouchListener) this);
		turnRightButton.setOnTouchListener((OnTouchListener) this);
		turnLeftButton.setOnTouchListener((OnTouchListener) this);	
		notesButton.setOnTouchListener((OnTouchListener) this);
		sizeUpButton.setOnTouchListener((OnTouchListener) this);
		sizeDownButton.setOnTouchListener((OnTouchListener) this);
		searchButton.setOnTouchListener((OnTouchListener) this);
		stickyNotesButton.setOnTouchListener((OnTouchListener) this);
		tocButton.setOnTouchListener((OnTouchListener) this);
		nightDayButton.setOnTouchListener((OnTouchListener) this);
		toggleButton.setOnTouchListener((OnTouchListener) this);
						
		bookOverlay.setVisibility(View.GONE);
		bookOverlay.setBackgroundColor(0);
		
		/** THESE VALUES allow Text elements to scale per device so objects do not consume to much screen space on smaller devices ! **/
        screenHeightInPixels = getWindowManager().getDefaultDisplay().getHeight();
        screenWidthInPixels = getWindowManager().getDefaultDisplay().getWidth();
		/***/
		
		/* Page progress Bar */
		progBar = (SeekBar)findViewById(R.id.progressBar);					//Page Progress Bar
		progBar.setMax(book.getPages().size()-1);							//Progress bar goes from 0 to Last Page
		progBar.setProgressDrawable(getResources().getDrawable(R.drawable.red_progress));
		pageProg = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		progressBar = new PageProgressBar(progBar, this);
		
		positionProgressToast();
		/**/
						
		/* Sticky Notes */
		stickyNotesButton = (ImageButton) findViewById(R.id.stickyNoteButton); //id given in the xml;
		
		ArrayList<StickyNote> thisPageStickies = book.getCurrentPage().getAllStickyNotes();
		
		/* Draw all sticky notes associated with the current page */
		for(int stick = 0; stick < thisPageStickies.size(); stick++)
		{
			ImageView stickyImage = new ImageView(this);
			stickyImage.setImageResource(R.drawable.sticky);
			
			AbsoluteLayout.LayoutParams imageLocation = new AbsoluteLayout.LayoutParams((int)(40 * bookContent.getScale()), (int)(40 * bookContent.getScale()), (int)thisPageStickies.get(stick).getXCoordinate(), (int)thisPageStickies.get(stick).getYCoordinate());
			
			stickyImage.setLayoutParams(imageLocation);
			stickyImage.setOnTouchListener((OnTouchListener) this);
			
			absoluteBookLayout.addView(stickyImage);
			
			displayedStickies.add(stickyImage);
		}
		
		/* Change icon in bookmarkButton based on whether or not the current Page is bookmarked */
		if(book.getCurrentPage().isBookmarked())
			bookmarkButton.setImageResource(R.drawable.icon_bookmarked);
		else
			bookmarkButton.setImageResource(R.drawable.icon_bookmark_add);
		        
		/* Page Navigation Area */
		chapterNavDisplay = (TextView)findViewById(R.id.chapterDisplay);
		pageNavDisplay = (TextView)findViewById(R.id.pageNumDisplay);
		
		pageNavDisplay.setText("" + book.getCurrentPage().getPageNum());
		chapterNavDisplay.setText(book.getChapter().getName());
		
		// Note! The initial Text Size was calculated on a 1024 x 600 pixel resolution (22px font).  This will scale to any device.
		pageNavDisplay.setTextSize(22 * (screenHeightInPixels/1024) * (screenWidthInPixels/600));
		chapterNavDisplay.setTextSize(22 * (screenHeightInPixels/1024) * (screenWidthInPixels/600));
		/**/
		
		searchForString = new Search(searchButton, closeButton, searchBar, pageNavDisplay, chapterNavDisplay);
		bookContent.setWebViewClient(new MyWebViewClient());
		
		bookContent.setWebChromeClient(new WebChromeClient() {
			@Override
			public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
				  new AlertDialog.Builder(appContext)  
				             .setTitle("Quiz")  
				             .setMessage(message)  
				             .setPositiveButton(android.R.string.ok,  
				                     new AlertDialog.OnClickListener()  
				                     {  
				                         public void onClick(DialogInterface dialog, int which)  
				                         {  
				                             result.confirm();  
				                         }  
				                     })  
				             .setCancelable(false)  
				             .create()  
				             .show();  
				   
				         return true;
		       }
		});
	
		/* Special behavior for Long Press on page turn buttons -- Navigate faster */
		turnLeftButton.setOnLongClickListener(this);
		turnRightButton.setOnLongClickListener(this);
		
	}//END onCreate

	//Function loads the previous settings 
	private void mySetup() throws IOException
	{
		/*****  I had to comment this out because it was causing problems every second time i compiled the app *******/
	
		int lineNum = 0;
		int size = 0;
		String line;
		try 
		{
		    // open the file for reading
			InputStream instream = openFileInput(book.getBookTitle()+".txt");
		 
		    // if file the available for reading
		    if(instream != null) 
		    {
		      // prepare the file for reading
		      InputStreamReader inputreader = new InputStreamReader(instream);
		      BufferedReader buffreader = new BufferedReader(inputreader);
		 
		      // read every line of the file into the line-variable, on line at the time
		      while ((line = buffreader.readLine()) != null) 
		      {
					if(lineNum == 0)
					{
						iMode = Integer.parseInt(line.trim());
					}
					else if(lineNum == 1)
					{
						fontSize = line.trim();
						ifontSize = Integer.parseInt(line.trim());
					}
					else if(lineNum == 2)
					{
						iLastPage = Integer.parseInt(line.trim());
					}
					else if(lineNum == 3)
					{//Get size of previous table of bookmarks
						size = Integer.parseInt(line.trim());
					}
					else
					{//Add bookmarks to table 
						Bookmark oneBookmark = new Bookmark(book.getPages().get(Integer.parseInt(line.trim())));
						tob.add(oneBookmark);
					}					
					lineNum++;
		      }
		 
		    }
		 
		    // close the file again
		    instream.close();
		  } catch (java.io.FileNotFoundException e) {
		    // do something if the myfilename.txt does not exits
		  }
		
		ndMode = iMode;
		if(ndMode == 1)
		{	
			FileRead.nightDay(true, book.getBookTitle().toString());
			bookContent.reload();
			//StyleChanger.writeContents(1, fontType, fontSize, fontFont, fontSrc);
			bookView.setBackgroundColor(Color.parseColor("Black"));
			containerView.setBackgroundColor(Color.parseColor("Black"));
			bookContent.setBackgroundColor(Color.parseColor("Black"));    			    			
			//bookNavToolView.setBackgroundColor(Color.parseColor("Black"));
		}
		else
		{
			FileRead.nightDay(false, book.getBookTitle().toString());
			bookContent.reload();
			//StyleChanger.writeContents(0, fontType, fontSize, fontFont, fontSrc);
			bookView.setBackgroundColor(Color.parseColor("White"));
			containerView.setBackgroundColor(Color.parseColor("White"));
			bookContent.setBackgroundColor(Color.parseColor("White"));    			
			//bookNavToolView.setBackgroundColor(Color.parseColor("White"));
		}
		bookView.refreshDrawableState();
		containerView.refreshDrawableState();
		bookNavToolView.refreshDrawableState();
		bookContent.loadUrl(book.getCurrentPage().getPageContent());
		bookContent.refreshDrawableState();
		

	}
	
	private class MyWebViewClient extends WebViewClient 
	{   
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) 
		{	
			currentNBPage.setTextOnPage(notesContent.getText()); //Save current Notebook info
			
			if (url.startsWith("image://")) 
			{
				String imageToShow = url.substring(8);
												
				try 
				{
					displayImageFullScreen(imageToShow);
				} 
				catch (IOException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			//Link Handling for Pages. Linking to other Pages will be done using a href of page://<pageName>
			//pageName is the name of the html document including the .html
			else if (url.startsWith("page://"))
			{
				String pageToShow = url.substring(7);
								
				for(int i = 0; i < book.getPages().size(); i++)
				{
					if(book.getPages().get(i).getPageName().equals(pageToShow))
					{
						Page reDirect = book.getPages().get(i);
						
						previousPage = book.getCurrentPage();
						jumpToPage(reDirect);
					}
				}
			}
			//Link Handling for Glossary Terms. Linking to terms will be done using a href of glossary://<termName>
			else if (url.startsWith("glossary://"))
			{
				String termToShow = (url.substring(11)).toLowerCase();
				shouldShowGlossary = true;
					
				//bun = getIntent().getExtras();
				//bun = new Bundle();
				//bun.putSerializable
				bun.putInt("bookIndex", book.getBookID());
				bun.putSerializable("Glossary", termToShow);
				bun.putSerializable("ShowGloss", shouldShowGlossary);
				
				initializeTables(tocButton);				
			}			
			else		// External Reference -- Will open in the External WebViewer
			{
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
				startActivity(browserIntent);

/*				if(!view.equals(browser))
				{
					try 
					{
						displayExternalWebPage(url);
												
						return false;
					} 
					catch (IOException e) 
					{
						e.printStackTrace();
					}
				}
				else
				{					
					view.loadUrl(url);
					addressBar.setText(url);
					
					resetWebButtons(webForward, webBack, webRefresh);
				}
*/	
			}
			return true;
		}
				
		/* Detects when a page has finished loading */
		@Override
		public void onPageFinished(WebView view, String url)
		{
			if(view.equals(browser))
			{
				addressBar.setText(view.getUrl());
				webLoading.setVisibility(View.INVISIBLE);
			}
			else if(view.equals(bookContent))
			{
				//System.out.println("Page finished loading");
				okayToAnchor = true;
			}
		}
		
		/* Detects when a page has begun loading */
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon)
		{
			if(view.equals(browser))
			{
				webLoading.setVisibility(View.VISIBLE);
			
				browser.setWebChromeClient(new WebChromeClient() 
				{
				    public void onProgressChanged(WebView view, int progress) 
				    {
				        webLoading.setProgress(0);
	
				        webLoading.incrementProgressBy(progress);
				    }
				});
			}
			else if(view.equals(bookContent))
			{
				okayToAnchor = false;
			}
		}
		
		
	}//END MyWebViewClient
	
	//*******TOC Menu Code (Press Menu button to view)*******
	@Override
	public void onAttachedToWindow() 
	{
	    super.onAttachedToWindow();
	    if(newload != 0)
	      openOptionsMenu();
	    
	    newload = 1;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.option, menu);
		return true;
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) 
	{
		menu.clear();
		addMenuStuff(menu);
		return super.onPrepareOptionsMenu(menu);
	}
	
	private void showMsg(String message) 
	{
		Toast msg = Toast.makeText(Main.this, message, Toast.LENGTH_LONG);
		msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2,
		msg.getYOffset() / 2);
		msg.show();
	}
	
	public void addMenuStuff(Menu menu)
	{ 	
		System.out.println("Pages Book: " + (int) book.numPages() + " Chapters: " + (int) book.numChapters()+ " Chapter: " + (book.getCurrentPage().getChapterName()));
		
		SubMenu chapterMenu = menu.addSubMenu("Table of Contents");
		SubMenu pagesMenu = menu.addSubMenu("Pages in Chapter");
		SubMenu bookmarkMenu = menu.addSubMenu("Bookmarks");
		
		int num = 0;
		int num2 = 0;
		int i = 0;
		int j = 0;
		int count = 0;
		String chapPrevTitle;
		String chapCurrTitle;
		int chapnum = 0;
		String str = null;
	
		//Build toc (all chapters pages items etc)
		CHAP_MENU_ITEM = menpos;
		num = (int) book.numPages();
		chapPrevTitle = (book.getPages().get(0).getChapterName());
		
		chapterMenu.add(CHAPTER, menpos, count, chapPrevTitle);
		chapnum = 0;
		count++;
		menpos++;
		
		for(i = 0; i < num; i++)
		{	
			chapCurrTitle = (book.getPages().get(i).getChapterName());
			if((chapCurrTitle == chapPrevTitle))
			{
				str = "\t\tPage " + Integer.toString((int) (i+1));
				chapterMenu.add(CHAPTER, menpos, count, str);
				count++;
				menpos++;
			}
			else
			{
				chapPrevTitle = chapCurrTitle;
				chapnum++;
				chapterMenu.add(CHAPTER, menpos, count, chapPrevTitle);
				count++;
				menpos++;
				
				str = "\t\tPage " + Integer.toString((int) (i+1));
				chapterMenu.add(CHAPTER, menpos, count, str);
				count++;
				menpos++;
			}
		}
		
		//Build toc (all chapters pages items etc)
		PAGE_MENU_ITEM = menpos;
		num = (int) book.numPages();
		num2 = (int) book.getCurrentPage().getPageNum() -1;
		chapPrevTitle = (book.getCurrentPage().getChapterName());
		
		chapnum = 0;
		count = 0;
		count++;
		menpos++;
		
		for(i = 0; i < num; i++)
		{	
			chapCurrTitle = (book.getPages().get(i).getChapterName());
			if((chapCurrTitle == chapPrevTitle))
			{
				str = "Page " + Integer.toString((int) (i+1));
				pagesMenu.add(PAGES, menpos, count, str);
				count++;
				menpos++;
			}
			else
			{
				
			}
		}
		
		BOOK_MENU_ITEM = menpos;
		num = tob.size();
		if(num == 0)
		{
			str = "No Bookmarks Added"; 
			bookmarkMenu.add(BOOKMARKS, menpos, i, str);
			menpos++;
		}
		else
		{
			for(i = 0; i < num; i++)
			{
				str = Integer.toString((int) tob.getBookmarkAt(i).getPageNum()); 
				bookmarkMenu.add(BOOKMARKS, menpos, i, str);
				menpos++;
			}
		}
	}//END addMenuStuff
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
/*		int code = 0;
		int bookPage = 0;
		int num1 = 0;
		int num2 = 0;
		int j = BOOK_MENU_ITEM;
		String str = null;
		
		for(int i = 0; i < tob.size(); i++)
		{
			if(item.getItemId() == j)
			{
				code = (int) book.getCurrentPage().getPageNum();
				showMsg("Page Number " + item.toString());
				str = item.toString();
				bookPage = Integer.parseInt(str.trim()) - 1;
				
				// the String to int conversion happens here
				book.setCurrentPage(book.getPages().get(bookPage));
				
				System.out.println("prevPage: " + code);
				//System.out.println("bookPage Page: " + bookPage);
				System.out.println("Redirecting to Page: " + book.getCurrentPage().getPageNum());
				
				//System.out.println("pagenum before: " + currentPageNum);
				currentPageNum = book.getCurrentPage().getPageNum();
				//System.out.println("pagenum after: " + currentPageNum);
				
				System.out.println("num1 = " + num1 + " " + num2 +" = num2");
				
				if(code == book.numPages() && currentPageNum != book.numPages())
				{
					turnRightButton.setClickable(true);
					turnRightButton.setTextColor(Color.parseColor("Black"));	//Re-enable Next Page button if disabled
					turnRightButton.setVisibility(View.VISIBLE);
					rightButtonIsClickable = true;
				}
				else if(code == 1 && currentPageNum == 1)
				{
					turnLeftButton.setClickable(false);
					turnLeftButton.setTextColor(Color.parseColor("Red"));	//Cannot go to Previous Page
					turnLeftButton.setVisibility(View.INVISIBLE);
					leftButtonIsClickable = false;
				}
				else
				{
					turnRightButton.setClickable(true);
					turnRightButton.setTextColor(Color.parseColor("Black"));	//Re-enable Next Page button if disabled
					turnRightButton.setVisibility(View.VISIBLE);
					rightButtonIsClickable = true;
					
					turnLeftButton.setClickable(true);
					turnLeftButton.setTextColor(Color.parseColor("Black"));	//Re-enable Next Page button if disabled
					turnLeftButton.setVisibility(View.VISIBLE);
					leftButtonIsClickable = true;
				}
				
				if(code < currentPageNum)
				{//Flip Left
					bookContent.loadUrl(book.getPages().get((int)currentPageNum-1).getPageContent());	// Displays last Page
					book.setCurrentPage(book.getPages().get((int)currentPageNum-1));
				}
				else if(code > currentPageNum)
				{//FlipRight
					bookContent.loadUrl(book.getPages().get((int) code - 1).getPageContent());	// Displays last Page
					book.setCurrentPage(book.getPages().get((int)currentPageNum-1));
				}			    
*/
				/* Change icon in bookmarkButton based on whether or not the current Page is bookmarked */
	
/*				if(book.getCurrentPage().isBookmarked())
					bookmarkButton.setImageResource(R.drawable.icon_bookmarked);
				else
					bookmarkButton.setImageResource(R.drawable.icon_bookmark_add);
			}
			++j;

		}
*/		
		return super.onOptionsItemSelected(item);
	}//END onOptionsItemSelected
	
	//*******END Option Menu Code*******	
	
	/**Select Text in the webview and automatically sends the selected text to the clipboard*/
	public void selectAndCopyText(View button) 
	{
		toolbarView.setVisibility(View.GONE);
		hideBrightnessBar();
		
				
		/*
        try
        {
        	Method m = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
			m.invoke(bookContent, true);
			
            KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
            shiftPressEvent.dispatch(bookContent);
            Toast.makeText(this, "select_text_now", Toast.LENGTH_SHORT).show();
        }
        catch (Exception e)
        {
            System.out.println("SELECT: Exception in emulateShiftHeld()");
        }*/

        toolbarView.setVisibility(View.VISIBLE);   
		highlighterButton.setVisibility(View.VISIBLE);
        highlighterButton.setOnTouchListener(this);
		
	}
	
	
	public void highlightText(View button)
	{
		selectAndCopyText(button);
		/*
		String newBook = "";
		clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
		
		FileInputStream pageIn = new FileInputStream(Environment.getExternalStorageDirectory() + "/Textbooks/" + book.getBookTitle() + "/Chapters/" + book.getFolderName() + "/" + book.getPageName());
		InputStream mybuffer = pageIn;
		DataInputStream datainput = new DataInputStream(mybuffer);
		
		while (datainput.available() != 0) 
		{
			String line = datainput.readLine();
			if(clipboard.getText().toString().contains(line) && line != "")
			{
				line = "<span style='background-color: #FFFF66'>" + line + "</span>" + "\n";
				System.out.println(line);
			
				newBook = newBook + line + "\n";
			}
			else
			{
				newBook = newBook + line;
				//System.out.print(newBook);
			}
		}
		
		try
		{
			FileOutputStream pageOut = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Textbooks/" + book.getBookTitle() + "/Chapters/" + book.getFolderName() + "/" + book.getPageName());
			DataOutputStream dataoutput = new DataOutputStream(pageOut);
			dataoutput.writeUTF(newBook);
			dataoutput.flush();
	        dataoutput.close();
        }
		catch (Exception e)	{}
        
		highlighterButton.setVisibility(View.GONE);
		bookContent.loadUrl("file:///" + Environment.getExternalStorageDirectory() + "/Textbooks/" + book.getBookTitle() + "/Chapters/" + book.getFolderName() + "/" + book.getPageName());
		bookContent.refreshDrawableState();
		bookContent.reload();
		*/
	}

	
	/** Handles orientation changes between portrait/landscape views 
	*   There is alot of code in this method, but it just maintains uniformity between orientations
	*   For example, if you are in night mode with large text on page 3 and your notebook is open, when the user
	*   turns the tablet, the same settings should be maintained.
	*   
	*   Notebook data is saved to file on configuration change! 
	**/
	@Override
	public void onConfigurationChanged(Configuration newConfig) 
	{
		/* Maintain Notebook text when configuration is changed by writing contents to a file */
		//myContentString = notesContent.getText().toString();
		//notebookFileStuff.writeContents(myContentString);
		/**/
		
		/** THESE VALUES allow Text elements to scale per device so objects do not consume to much screen space on smaller devices ! **/
        screenHeightInPixels = getWindowManager().getDefaultDisplay().getHeight();
        screenWidthInPixels = getWindowManager().getDefaultDisplay().getWidth();
		/***/
		
		super.onConfigurationChanged(newConfig);
		
		System.out.println("SHOULD NOTES BE OPEN? -- " + areNotesVisible);
		System.out.println("VIEW GONE = " + View.GONE);
		System.out.println("VIEW VISIBLE = " + View.VISIBLE);
		
		if(displayingImageFullScreen)
		{
			setContentView(R.xml.full_image);
		
			try
			{
				displayImageFullScreen(imageOnDisplay);
			}
			catch(IOException e){}
			return;
		}
		else
		{
			setContentView(R.layout.main);
		}
		
		notesButton = (ImageButton) findViewById(R.id.notebookbutton); //id given in the xml
		sizeUpButton = (ImageButton) findViewById(R.id.biggerTextButton); //id given in the xml
		sizeDownButton = (ImageButton) findViewById(R.id.smallerTextButton); //id given in the xml
		tocButton = (ImageButton) findViewById(R.id.tableOfContentsButton); //id given in the xml
		nightDayButton = (ImageButton) findViewById(R.id.nightDay); //id given in the xml
		bookmarkButton = (ImageButton) findViewById(R.id.bookmarkButton); //id given in the xml
		searchButton = (ImageButton) findViewById(R.id.searchButton);
		stickyNotesButton = (ImageButton) findViewById(R.id.stickyNoteButton);
		closeButton = (Button) findViewById(R.id.closeSearchButton);
		searchBar = (EditText) findViewById(R.id.search);
		brightnessBar = (SeekBar) findViewById(R.id.brightnessBar);
		toggleButton = (ImageButton) findViewById(R.id.toggle);
		
		BrightnessSettings bright = new BrightnessSettings(this, brightnessBar, getWindow(), getContentResolver());
		
		
		/* Progress Bar Settings */
		progBar = (SeekBar)findViewById(R.id.progressBar);					//Page Progress Bar
		progBar.setMax(book.getPages().size()-1);							//Progress bar goes from 0 to Last Page
		progBar.setProgressDrawable(getResources().getDrawable(R.drawable.red_progress));
		pageProg = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		progressBar = new PageProgressBar(progBar, this);
		
		positionProgressToast();
		/**/
						
		/* Page Navigation Area */
		chapterNavDisplay = (TextView)findViewById(R.id.chapterDisplay);
		pageNavDisplay = (TextView)findViewById(R.id.pageNumDisplay);
		
		pageNavDisplay.setText("" + book.getCurrentPage().getPageNum());
		chapterNavDisplay.setText(book.getChapter().getName());
		
		// Note! The initial Text Size was calculated on a 1024 x 600 pixel resolution (22px font).  This will scale to any device.
		pageNavDisplay.setTextSize(22 * (screenHeightInPixels/1024) * (screenWidthInPixels/600));
		chapterNavDisplay.setTextSize(22 * (screenHeightInPixels/1024) * (screenWidthInPixels/600));
		/**/
		
		notesView = (LinearLayout) findViewById(R.id.viewnotes); //id of notesview in xml
		bookView = (LinearLayout) findViewById(R.id.viewmain);
		containerView = (LinearLayout) findViewById(R.id.container);
		toolbarView = (LinearLayout) findViewById(R.id.toolbar);
		globalView = (LinearLayout) findViewById(R.id.viewhome);
		bookNavToolView = (RelativeLayout) findViewById(R.id.bookNav);
		progressView = (RelativeLayout) findViewById(R.id.progressview);
		bookContent = (WebView) findViewById(R.id.booktext);
		notesContent = (EditText) findViewById(R.id.notebook);
		notesView.setVisibility(areNotesVisible);
		textBookContent = book.getCurrentPage().getPageText();
		//noteBookContent = notesContent.getText();
		//notesContent.setText(noteBookContent); 
		bookOverlay = (WebView) findViewById(R.id.bookOverlay);
		
		absoluteBookLayout = (AbsoluteLayout)findViewById(R.id.absoluteBook);
		
		
		/* Notebook Tab Initialization */ 
		closeNotebook = (ImageButton) findViewById(R.id.closeNotebook);
		tabLayout = (RelativeLayout) findViewById(R.id.tablayout);
		tabLayout2 = (LinearLayout) findViewById(R.id.tablayout2);
		tabScrollview = (HorizontalScrollView) findViewById(R.id.scrolltabs);
		tab = new Tabs(tabLayout, tabLayout2, tabScrollview, closeNotebook, notesView);
		theNotebook = book.getNotebook();
		notebookTabTouch = new NotebookTabTouch(this);
		
		allNBTabs = new ArrayList<TextView>();
						
		numberOfTabs = theNotebook.getNumNotebookPages();
		System.out.println("Number of PAGES = " + theNotebook.getNumNotebookPages());
		System.out.println("Number of TABS = " + numberOfTabs);
				
		for(int tab = 0; tab < theNotebook.getNumNotebookPages(); tab++)
		{
			TextView newtab = new TextView(this);
			LinearLayout.LayoutParams layoutP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			layoutP.setMargins(3,0,0,0);
			newtab.setPadding(10,5,10,5);
			newtab.setLayoutParams(layoutP);
			newtab.setText(theNotebook.getNBPage(tab).getTabLabel());
			
			System.out.println("Tab #" + tab + "Label: " + newtab.getText());
						
			//if(tab == theNotebook.getNumNotebookPages() - 1)
			if(tab == currentTabNum)
			{
				newtab.setBackgroundColor(Color.parseColor("#FFCC0000"));
				newtab.setTextColor(Color.parseColor("#FFFFFFFF"));
				newtab.setTextSize(18);
				
				// Set appropriate content in Notebook, and place cursor at end of last note. 
				notesContent.setText(theNotebook.getNBPage(tab).getTextOnPage());
				Editable notes = main.notesContent.getText(); 
				int position = notes.length(); 
				Selection.setSelection(notes, position); 

				currentTab = newtab;
				currentTabNum = tab;
				currentNBPage = theNotebook.getNBPage(tab);
			}
			else
			{
				newtab.setBackgroundColor(Color.parseColor("#FF980000"));
				newtab.setTextColor(Color.parseColor("#FFCCCCCC"));
				newtab.setTextSize(14);
			}
			
			notebookTabTouch.initializeTabSettings(newtab);
			tabLayout2.addView(newtab);
			
			allNBTabs.add(newtab);	
		}
		
		TextView addTabButton = new TextView(this);
		LinearLayout.LayoutParams addTabLayout = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		addTabLayout.setMargins(3,5,0,0);
		addTabButton.setPadding(10,0,10,0);
		addTabButton.setBackgroundColor(Color.parseColor("#FF980000"));
		addTabButton.setTextColor(Color.parseColor("#FFFFFFFF"));
		addTabButton.setLayoutParams(addTabLayout);
		addTabButton.setTextSize(20);
		addTabButton.setTypeface(Typeface.DEFAULT_BOLD);
		addTabButton.setText("+");
		
		addTabButton.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v) 
			{
				System.out.println("Child Count:" + tabLayout2.getChildCount());
				tabLayout2.removeViewAt(tabLayout2.getChildCount() - 1);
				
				addNotebookTab();
				
				tabLayout2.addView(v);
			}
		});
				
		tabLayout2.addView(addTabButton);
		
		
		/**/
								 
		turnRightButton = (Button) findViewById(R.id.pageRightButton); //id given in the xml;
		turnLeftButton = (Button) findViewById(R.id.pageLeftButton); //id given in the xml;
		
		/* Set the margin of the Toolbar using FrameLayout Params */
		FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.NO_GRAVITY);
	    layoutParams.setMargins(0, getDensityPixels(48), 0, 0);
	    toolbarView.setLayoutParams(layoutParams);
		
	    highlighterButton = (ImageButton) findViewById(R.id.highlightButton);
		highlighterButton.setVisibility(View.VISIBLE);
		
		scrollLength = getWindowManager().getDefaultDisplay().getWidth() / 3;
		bookContent.getSettings().setLightTouchEnabled(true);
		bookContent.getSettings().setJavaScriptEnabled(true);
		WebSettings settings = bookContent.getSettings();
		settings.setJavaScriptEnabled(true); 
		settings.setPluginsEnabled(true); 
		bookContent.getSettings().setUseWideViewPort(true);		   //Double-Tap .. Zoom in like an image, don't just change text size
		bookContent.getSettings().setLoadWithOverviewMode(true);
		bookContent.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL); 
		bookContent.setInitialScale(1);//Fit content to screen
		bookContent.setOnTouchListener(new OnTouchListener()
		{
			private int ScrollX1;
			private int ScrollX2;
			private int ScrollY1;
			private int ScrollY2;
			
			public boolean onTouch(View v, MotionEvent evt) 
			{				
				if (evt.getAction() == MotionEvent.ACTION_DOWN ||
			            evt.getAction() == MotionEvent.ACTION_POINTER_DOWN ||
			            evt.getAction() == MotionEvent.ACTION_POINTER_1_DOWN ||
			            evt.getAction() == MotionEvent.ACTION_POINTER_2_DOWN ||
			            evt.getAction() == MotionEvent.ACTION_POINTER_3_DOWN) {
					
						initialZoom = bookContent.getScale();
			            
						if(evt.getPointerCount() >= 3)
						{
							;
						}
						else if (evt.getPointerCount() > 1 && evt.getPointerCount() < 3) 
						{
							System.out.println("Two Fingers touching Book Content");
							
			            	bookContent.getSettings().setBuiltInZoomControls(true);
			                bookContent.getSettings().setSupportZoom(true);
			            }
						else
						{		                
							lastTouchX = evt.getX(); 
					        lastTouchY = evt.getY();
					        downXValue = evt.getX();
					        downTime = evt.getEventTime();
					        hasMoved = false;
					        ScrollX1 = bookContent.getScrollX();
					        ScrollY1 = bookContent.getScrollY();
					        
					        System.out.println("CurrentScrollPos = " + ScrollX1);
					        System.out.println("CurrentScale = " + initialZoom);
				 		}
				 }

			     if(evt.getAction() == MotionEvent.ACTION_MOVE)
			     {
			    	 if(evt.getPointerCount() >= 3)
					 {
						;
					 }
					 else if (evt.getPointerCount() > 1 && evt.getPointerCount() < 3)
			    	 {
			    		 ScrollX2 = bookContent.getScrollX();
			    		 ScrollY2 = bookContent.getScrollY();
			    		 			    		 
			    		 float currentZoom = bookContent.getScale();
			    		 			    		 			    		 
			    		 if(currentZoom != initialZoom)
			    		 {			    			 
			    			 if(book.getCurrentPage().hasStickyNotes())
			    			 {
			    				 ArrayList<StickyNote> allStickies = book.getCurrentPage().getAllStickyNotes();
			    				 
			    				 for(int stick = 0; stick < allStickies.size(); stick++)
			    				 {
		    						 int newScrollX = (int)((book.getCurrentPage().getAllStickyNotes().get(stick).getXCoordinate()*currentZoom/initialZoom - book.getCurrentPage().getAllStickyNotes().get(stick).getXCoordinate()) + (ScrollX1 * currentZoom/initialZoom) - ScrollX2);
				    				 int newScrollY = (int)((book.getCurrentPage().getAllStickyNotes().get(stick).getYCoordinate()*currentZoom/initialZoom - book.getCurrentPage().getAllStickyNotes().get(stick).getYCoordinate()) + (ScrollY1 * currentZoom/initialZoom) - ScrollY2);		    				 
			    				 
				    				 redrawSingleStickyNote(stick, newScrollX, newScrollY);
			    				 }
			    			 }
			    		 }
			    	 }
			    	 else
			    	 {
			    		 hasMoved = moved(evt); 
			    		 			         
			    		 ScrollX2 = bookContent.getScrollX();
			    		 ScrollY2 = bookContent.getScrollY();
			         
			    		 if(ScrollX2 != ScrollX1 || ScrollY2 != ScrollY1)
			    		 {
			    			 if(book.getCurrentPage().hasStickyNotes())
			    			 {
			    				 redrawStickyNotes(ScrollX1 - ScrollX2, ScrollY1 - ScrollY2);
			    			 }
			    		 }
			    	 }
			     }
			     
			     if (evt.getAction() == MotionEvent.ACTION_UP ||
				            evt.getAction() == MotionEvent.ACTION_POINTER_UP ||
				            evt.getAction() == MotionEvent.ACTION_POINTER_1_UP ||
				            evt.getAction() == MotionEvent.ACTION_POINTER_2_UP ||
				            evt.getAction() == MotionEvent.ACTION_POINTER_3_UP){
			    	   
			    	   bookContent.getSettings().setBuiltInZoomControls(false);
		               bookContent.getSettings().setSupportZoom(false);
			        
		               float currentX = evt.getX();
			           long currentTime = evt.getEventTime();
			           float difference = Math.abs(downXValue - currentX);
			           long time = currentTime - downTime;
			           ScrollX2 = bookContent.getScrollX();
			           ScrollY2 = bookContent.getScrollY();
			           
			           float currentZoom = bookContent.getScale();
			           
			           if(evt.getPointerCount() > 1)
			           {    		  
			        	   System.out.println("Still another finger touching");
			        	   
				    		 if(currentZoom != initialZoom)
				    		 {		        	   
			        	   
				    			 if(book.getCurrentPage().hasStickyNotes())
				    			 {
				    				 ArrayList<StickyNote> allStickies = book.getCurrentPage().getAllStickyNotes();
				    				 for(int s = 0; s < allStickies.size(); s++)
				    				 {
				    					 StickyNote sNote = allStickies.get(s);
				    					 
				    					 int newScrollX = (int)((sNote.getXCoordinate()*currentZoom/initialZoom - sNote.getXCoordinate()) + (ScrollX1 * currentZoom/initialZoom) - ScrollX2);
					    				 int newScrollY = (int)((book.getCurrentPage().getAllStickyNotes().get(s).getYCoordinate()*currentZoom/initialZoom - book.getCurrentPage().getAllStickyNotes().get(s).getYCoordinate()) + (ScrollY1 * currentZoom/initialZoom) - ScrollY2);
				    				 					    				 
				    					 sNote.setCoordinates((float)(sNote.getXCoordinate() + newScrollX), (float)(sNote.getYCoordinate() + newScrollY));
				    				 }
				    				 
				    				redrawStickyNotes(0,0);
				    			 }
				    			 
					        	   ScrollX1 = bookContent.getScrollX();
						    	   ScrollY1 = bookContent.getScrollY();
				    		 }
				    	}
				    	else
				    	{
				    		 hasMoved = moved(evt); 
				    		 
				    		 System.out.println("Only one finger lifted");
				    		 
				    		 flinger = new Thread(main);
				    		 flinger.start();
				         			         
				    		 if(ScrollX2 != ScrollX1 || ScrollY2 != ScrollY1)
				    		 {
				    			 if(book.getCurrentPage().hasStickyNotes())
				    			 {
				    				 ArrayList<StickyNote> allStickies = book.getCurrentPage().getAllStickyNotes();
				    				 for(int s = 0; s < allStickies.size(); s++)
				    				 {
				    					 StickyNote sNote = allStickies.get(s);
				    				 
				    					 sNote.setCoordinates((float)((sNote.getXCoordinate() + ScrollX1 - ScrollX2)), (float)((sNote.getYCoordinate() + ScrollY1 - ScrollY2)));
				    				 }
				    				 
				    				 redrawStickyNotes(0,0);
				    			 }
				    		 }
				    	}
			           

			           Log.i("Touch Event:",  "Distance: " + difference + "px Time: " + time + "ms");
			           	 
			             if(ScrollX1 == ScrollX2 && ScrollY1 == ScrollY2 && (time < 150) && (difference < 30))
			             {	            	 
			            	 if(!book.getPageName().contains("Quiz") && !book.getPageName().contains("quiz"))
			            	 {
				            	 if(bookNavToolView.getVisibility() == View.GONE)
				            	 {
				            		 bookNavToolView.setVisibility(View.VISIBLE);
					            	 progressView.setVisibility(View.VISIBLE);
					            	 
					            	 if(toolbarOpen)
					            	     toolbarView.setVisibility(View.VISIBLE);
					            	 
					             }
				            	 else
				            	 {
				            		 bookNavToolView.setVisibility(View.GONE);
					            	 progressView.setVisibility(View.INVISIBLE);
					            	 toolbarView.setVisibility(View.GONE);
					            	 hideBrightnessBar();
				            	 }
			            	 }
			             }
			           
				         if ( (downXValue < currentX) && (time < 400) && (difference > 100) && bookContent.getScrollX() == 0 && currentPageNum != 1) {
				               turnPage(turnLeftButton);
				         }

			             if ( (downXValue > currentX) && (time < 400) && (difference > 100) && ScrollX1 == ScrollX2 && currentPageNum != book.numPages() ) {
			                   turnPage(turnRightButton);
		                  }
			             
			         } 		     		
			     	
			         return false;
				}
				
				 float downXValue;
				 long downTime;
			     private float lastTouchX, lastTouchY; 
			     private boolean hasMoved = false; 
			     private boolean moved(MotionEvent evt) { 
			     return hasMoved || Math.abs(evt.getX() - lastTouchX) > 10.0 || Math.abs(evt.getY() - lastTouchY) > 10.0; 
			 }
				
		});
		
		bookContent.loadUrl(book.getPages().get((int)currentPageNum-1).getPageContent());		//Set first View to first Page
		book.setCurrentPage(book.getPages().get((int)currentPageNum-1));
				
		if(leftButtonIsClickable)
		{
			turnLeftButton.setClickable(true);
			turnLeftButton.setTextColor(Color.parseColor("Black"));
			turnLeftButton.setVisibility(View.VISIBLE);
		}
		else
		{
			turnLeftButton.setClickable(false);
			turnLeftButton.setTextColor(Color.parseColor("Red"));
			turnLeftButton.setVisibility(View.INVISIBLE);
		}
		
		if(rightButtonIsClickable)
		{
			turnRightButton.setClickable(true);
			turnRightButton.setTextColor(Color.parseColor("Black"));
			turnRightButton.setVisibility(View.VISIBLE);
		}
		else
		{
			turnRightButton.setClickable(false);
			turnRightButton.setTextColor(Color.parseColor("Red"));
			turnRightButton.setVisibility(View.INVISIBLE);
		}
		
		bookView.setOnTouchListener((OnTouchListener) this);			//Touch Listener for TextBook pages
		bookOverlay.setOnTouchListener((OnTouchListener) this);
		
		//bookContent.setOnTouchListener((OnTouchListener) this);			//Touch Listener for TextBook pages		
		turnRightButton.setOnTouchListener((OnTouchListener) this);
		turnLeftButton.setOnTouchListener((OnTouchListener) this);
		notesButton.setOnTouchListener((OnTouchListener) this);
		sizeUpButton.setOnTouchListener((OnTouchListener) this);
		sizeDownButton.setOnTouchListener((OnTouchListener) this);
		searchButton.setOnTouchListener((OnTouchListener) this);
		stickyNotesButton.setOnTouchListener((OnTouchListener) this);
		tocButton.setOnTouchListener((OnTouchListener) this);
		nightDayButton.setOnTouchListener((OnTouchListener) this);
		toggleButton.setOnTouchListener((OnTouchListener) this);
		
		
		bookOverlay.setVisibility(View.GONE);
		bookOverlay.setBackgroundColor(0);
		
		/* Sticky Notes */
		stickyNotesButton = (ImageButton) findViewById(R.id.stickyNoteButton); //id given in the xml;
		ArrayList<StickyNote> thisPageStickies = book.getCurrentPage().getAllStickyNotes();
		
		/* Draw all sticky notes associated with the current page */
		for(int stick = 0; stick < thisPageStickies.size(); stick++)
		{
			ImageView stickyImage = new ImageView(this);
			stickyImage.setImageResource(R.drawable.sticky);
			AbsoluteLayout.LayoutParams imageLocation = new AbsoluteLayout.LayoutParams((int)(40 * bookContent.getScale()), (int)(40 * bookContent.getScale()), (int)thisPageStickies.get(stick).getXCoordinate(), (int)thisPageStickies.get(stick).getYCoordinate());
			
			stickyImage.setLayoutParams(imageLocation);
			stickyImage.setOnTouchListener((OnTouchListener) this);
			
			absoluteBookLayout.addView(stickyImage);
			
			displayedStickies.add(stickyImage);
		}
		
		/* Change icon in bookmarkButton based on whether or not the current Page is bookmarked */
		if(book.getCurrentPage().isBookmarked())
			bookmarkButton.setImageResource(R.drawable.icon_bookmarked);
		else
			bookmarkButton.setImageResource(R.drawable.icon_bookmark_add);
			
		searchForString = new Search(searchButton, closeButton, searchBar, pageNavDisplay, chapterNavDisplay);
		
		if(isSearchBarVisible == true)
			searchForString.showSearchBar();

		previousPage = book.getCurrentPage();
		jumpToPage(book.getPages().get((int)currentPageNum-1));
				
		bookContent.setWebViewClient(new MyWebViewClient());
		
		bookContent.setWebChromeClient(new WebChromeClient() {
			@Override
			public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
				new AlertDialog.Builder(appContext)  
	             .setTitle("Quiz")  
	             .setMessage(message)  
	             .setPositiveButton(android.R.string.ok,  
	                     new AlertDialog.OnClickListener()  
	                     {  
	                         public void onClick(DialogInterface dialog, int which)  
	                         {  
	                             result.confirm();  
	                         }  
	                     })  
	             .setCancelable(false)  
	             .create()  
	             .show();  
	   
	             return true;

		       }
		});
	}//END onConfigurationChanged
	
	public void myClick(View button)
	{   		
		if(brightnessBar.getVisibility() == View.VISIBLE)
			hideBrightnessBar();
		
		if(button.equals(notesButton))
		{
			if(notesView.getVisibility() == View.VISIBLE)
			{
				//myContentString = notesContent.getText().toString();
				//notebookFileStuff.writeContents(myContentString);
				notesView.setVisibility(View.GONE);
				tab.hideTabs();
			}
			else
			{
				toolbarView.setVisibility(View.GONE);
				hideBrightnessBar();
				bookNavToolView.setVisibility(View.GONE);
				toggleButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_manage));
				progressView.setVisibility(View.GONE);
				notesView.setVisibility(View.VISIBLE);
				
				tab.showTabs();
			}
			areNotesVisible = notesView.getVisibility();
		}
		else if(button.equals(closeNotebook))
		{
			notesView.setVisibility(View.GONE);
			tab.hideTabs();
			areNotesVisible = notesView.getVisibility();
		}
		else if(button.equals(sizeUpButton))
		{
			String currentContent = bookContent.getUrl();
			
			System.out.println("Pressed Size Up Button");
			WebSettings settings = bookContent.getSettings();
			int currFontSize = settings.getDefaultFontSize();
			settings.setDefaultFontSize(currFontSize+5);
			
			/*FileRead.changeSize(true, book.getBookTitle().toString());
			bookContent.reload();
			bookView.refreshDrawableState();
			containerView.refreshDrawableState();
			bookNavToolView.refreshDrawableState();
			//bookContent.loadUrl(book.getCurrentPage().getPageContent());
			bookContent.loadUrl(currentContent);
			bookContent.refreshDrawableState();
			*/
		}
		else if(button.equals(sizeDownButton))
		{
			String currentContent = bookContent.getUrl();
			
			System.out.println("Pressed Size Down Button");
			WebSettings settings = bookContent.getSettings();
			int currFontSize = settings.getDefaultFontSize();
			settings.setDefaultFontSize(currFontSize-5);
			
			/*
			FileRead.changeSize(false, book.getBookTitle().toString());
			bookContent.reload();
			bookView.refreshDrawableState();
			containerView.refreshDrawableState();
			bookNavToolView.refreshDrawableState();
			bookContent.loadUrl(currentContent);
			bookContent.refreshDrawableState();
			*/
		}
		else if(button.equals(tocButton))
		{
			openOptionsMenu();
		}
		
		textBookContent = bookContent.getUrl();
		//noteBookContent = notesContent.getText();
	}//END myClick
	
	
	public boolean toggleNightDay()
	{
		String currentContent = bookContent.getUrl();

		if(ndMode == 0)
		{
			ndMode = 1;
			FileRead.nightDay(true, book.getBookTitle().toString());
			bookContent.reload();
			bookView.setBackgroundColor(Color.parseColor("Black"));
			containerView.setBackgroundColor(Color.parseColor("Black"));
			bookContent.setBackgroundColor(Color.parseColor("Black"));    			    			
		}
		else
		{
			ndMode = 0;
			FileRead.nightDay(false, book.getBookTitle().toString());
			bookContent.reload();
			bookView.setBackgroundColor(Color.parseColor("White"));
			containerView.setBackgroundColor(Color.parseColor("White"));
			bookContent.setBackgroundColor(Color.parseColor("White"));    			
		}

		bookView.refreshDrawableState();
		containerView.refreshDrawableState();
		bookNavToolView.refreshDrawableState();
		bookContent.refreshDrawableState();

		return true;
	}
	
	/**  This function is a stand-in to test Bookmark functionality.  In final program, when a new Book is created, the 
	*   Book will have created a TableOfBookmarks, and this class will therefore not need to 
	*/
	public void bookmarkClick(View button)
	{
		Bookmark oneBookmark = new Bookmark(book.getCurrentPage());
		
		// Only adds a new bookmark if it can't remove the bookmark - meaning it hasn't already been set.
		if(tob.remove(oneBookmark) == false)
		{
			tob.add(oneBookmark);
		}
		
		/* Change icon in bookmarkButton based on whether or not the current Page is bookmarked */
		if(book.getCurrentPage().isBookmarked())
		{
			bookmarkButton.setImageResource(R.drawable.icon_bookmarked);
			
			for(int b = 0; b < book.numPages(); b++)
			{
				if(book.getPages().get(b).isBookmarked())
					System.out.println("Page " + book.getPages().get(b) + " is bookmarked in Book");
				else
					System.out.println("Page " + book.getPages().get(b) + " is NOT bookmarked in Book");
			}
			
			for(int c = 0; c < book.getChapter().numPages(); c++)
			{
				if(book.getChapter().getPages().get(c).isBookmarked())
					System.out.println("Page " + book.getChapter().getPages().get(c) + " is bookmarked in Chapter");
				else
					System.out.println("Page " + book.getChapter().getPages().get(c) + " is NOT bookmarked in Chapter");
			}
		}
		else
			bookmarkButton.setImageResource(R.drawable.icon_bookmark_add);
		
		if(brightnessBar.getVisibility() == View.VISIBLE)
			hideBrightnessBar();
	}   
	
	/** This method controls the behavior of pressing the StickyNote button */
	public void attachStickyNote(View button)
	{
		//If there is already a pending Sticky note, do not create a new one until the first is placed.
		if(pendingSticky)
			return;
		
		oneSticky = new StickyNote();
		final StickyNote oneNote = oneSticky;
		
		stickyNote = new Dialog(this);
		LinearLayout stickyLayout = new LinearLayout(this);
		final EditText stickyText = new EditText(this);
		
		LinearLayout buttonLayout = new LinearLayout(this);
		Button placeButton = new Button(this);
		Button cancelButton = new Button(this);
		
		LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
		buttonParams.setMargins(3, 3, 3, 3);
		placeButton.setLayoutParams(buttonParams);
		cancelButton.setLayoutParams(buttonParams);
		
		/*
		|---------------------|
		|     stickyNote	  |
		|---------------------|
		|     stickyLayout    |
		|                     |
		|      stickyText     |
		|                     |
		|                     |
		|  -----------------  |
		|     buttonLayout    |
		| | Place |  |Cancel| |
		|---------------------|
		*/
		
		stickyLayout.setOrientation(VERTICAL);
		stickyLayout.setBackgroundColor(Color.parseColor("#FFFFF68F"));
		
		buttonLayout.setOrientation(HORIZONTAL);
		buttonLayout.setBackgroundColor(Color.parseColor("#FFFFF68F"));
		
		stickyText.setBackgroundColor(Color.parseColor("#FFFFF68F"));
		stickyText.setTextColor(Color.parseColor("Black"));
		stickyText.setPadding(10,10,10,10);
		stickyText.setGravity(Gravity.TOP);
		
		if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
		{
			stickyText.setWidth(this.screenWidthInPixels / 2);
			stickyText.setHeight(this.screenHeightInPixels / 5);
		}
		else
		{
			stickyText.setWidth(globalView.getWidth() / 2);
			stickyText.setHeight(globalView.getHeight() / 3);
		}
		
		buttonLayout.addView(placeButton);
		buttonLayout.addView(cancelButton);
		stickyLayout.addView(stickyText);
		stickyLayout.addView(buttonLayout);
		
		placeButton.setText("Place");
		placeButton.setTextColor(Color.parseColor("Black"));
		
		cancelButton.setText("Cancel");
		cancelButton.setTextColor(Color.parseColor("Black"));
		
		/* Action that occurs when you click the Place button */
		placeButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				oneNote.setText(stickyText.getText());
				oneNote.setPage(book.getCurrentPage());
				pendingSticky = true;
				stickyNote.cancel();
				
				bookOverlay.setVisibility(View.VISIBLE);
			}
		});
		
		/* Action that occurs when you click the Cancel button */
		cancelButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				stickyNote.cancel();
			}
		});
		//cancelButton.setOnClickListener((OnClickListener) this);			//Click listener for Sticky Note button
		
		stickyNote.setContentView(stickyLayout);
		stickyNote.show();
		
		if(brightnessBar.getVisibility() == View.VISIBLE)
			hideBrightnessBar();
	}//END attachStickyNote
	
	/** Toggle the Display of the Toolbar */
	public void toggleToolbar(View button)
	{
		if(button.equals(toggleButton))
		{
			if(toolbarView.getVisibility() == View.VISIBLE)
			{
				toolbarView.setVisibility(View.GONE);
				hideBrightnessBar();
				toggleButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_manage));
				toolbarOpen = false;
			}
			else
			{
				toolbarView.setVisibility(View.VISIBLE);
				toggleButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_manage_close));
				toolbarOpen = true;
			}
			
		}
		
		if(brightnessBar.getVisibility() == View.VISIBLE)
			hideBrightnessBar();
	}
	
	/** Handles Page turning when appropriate buttons are pressed */
	public void turnPage(View button)
	{   		
		searchForString.resetSearchProgress();
		
		if(brightnessBar.getVisibility() == View.VISIBLE)
			hideBrightnessBar();
		
		WebSettings settings = bookContent.getSettings();
		int currFontSize = settings.getDefaultFontSize();
				
		/* Remove all sticky notes associated with the current page before turning */
		for(int stick = 0; stick < displayedStickies.size(); stick++)
		{
			absoluteBookLayout.removeView(displayedStickies.get(stick));
		}
		displayedStickies.clear();
		    		    		        	    	
		if(button.equals(turnRightButton))								/* Display next Page */
		{
			//System.out.println(book.numPages());
						
			currentPageNum++;
			progBar.setProgress((int)currentPageNum-1);
			
			turnLeftButton.setClickable(true);
			turnLeftButton.setTextColor(Color.parseColor("Black"));		// Re-enable Previous Page button if disabled
			turnLeftButton.setVisibility(View.VISIBLE);
			leftButtonIsClickable = true;
			
			if(currentPageNum == book.numPages())						// Last Page?
			{
				turnRightButton.setClickable(false);		
				turnRightButton.setTextColor(Color.parseColor("Red"));	// Cannot go to Next Page
				turnRightButton.setVisibility(View.INVISIBLE);
				turnRightButton.setPressed(false);						// Stops long-press fast-scrolling
				rightButtonIsClickable = false;
				
				bookContent.loadUrl(book.getPages().get((int)currentPageNum-1).getPageContent());	// Displays last Page
				
				book.setCurrentPage(book.getPages().get((int)currentPageNum-1));
			}
			else if(currentPageNum >= 2)								// Not Last Page
			{
				bookContent.loadUrl(book.getPages().get((int)currentPageNum-1).getPageContent());	// Displays last Page
				book.setCurrentPage(book.getPages().get((int)currentPageNum-1));
			}
		}
		else															/* Display Previous Page */
		{
			currentPageNum--;
			progBar.setProgress((int)currentPageNum-1);
				
			turnRightButton.setClickable(true);
			turnRightButton.setTextColor(Color.parseColor("Black"));	//Re-enable Next Page button if disabled
			turnRightButton.setVisibility(View.VISIBLE);
			rightButtonIsClickable = true;
			
			if(currentPageNum == 1)										// First Page?
			{
				turnLeftButton.setClickable(false);
				turnLeftButton.setTextColor(Color.parseColor("Red"));	//Cannot go to Previous Page
				turnLeftButton.setVisibility(View.INVISIBLE);
				turnLeftButton.setPressed(false);						// Stops long-press fast-scrolling
				leftButtonIsClickable = false;
				
				bookContent.loadUrl(book.getPages().get((int)currentPageNum-1).getPageContent());	// Displays first Page
				book.setCurrentPage(book.getPages().get((int)currentPageNum-1));
			}
			else if(currentPageNum <= book.numPages()-1)				// Not First Page
			{
				bookContent.loadUrl(book.getPages().get((int)currentPageNum-1).getPageContent()); //Previous Page
				book.setCurrentPage(book.getPages().get((int)currentPageNum-1));
			}
		}
		
			System.out.println("Current Page = " + book.getCurrentPage().getPageName());
		
			ArrayList<StickyNote> thisPageStickies = book.getCurrentPage().getAllStickyNotes();
			//thisPageStickies = book.getCurrentPage().getAllStickyNotes();
			
			if(thisPageStickies.size() != 0)
			{
				// Draw all sticky notes associated with the current page //
				for(int stick = 0; stick < thisPageStickies.size(); stick++)
				{
					ImageView stickyImage = new ImageView(this);
					stickyImage.setImageResource(R.drawable.sticky);
					
					AbsoluteLayout.LayoutParams imageLocation = new AbsoluteLayout.LayoutParams((int)(40 * bookContent.getScale()), (int)(40 * bookContent.getScale()), (int)thisPageStickies.get(stick).getXCoordinate(), (int)thisPageStickies.get(stick).getYCoordinate());
					
					stickyImage.setLayoutParams(imageLocation);
					stickyImage.setOnTouchListener((OnTouchListener) this);
					
					absoluteBookLayout.addView(stickyImage);
					displayedStickies.add(stickyImage);
				}
			}
		
		/* Change icon in bookmarkButton based on whether or not the current Page is bookmarked */
		if(book.getCurrentPage().isBookmarked())
			bookmarkButton.setImageResource(R.drawable.icon_bookmarked);
		else
			bookmarkButton.setImageResource(R.drawable.icon_bookmark_add);
		
		positionProgressToast();
								
		pageNavDisplay.setText("" + book.getCurrentPage().getPageNum());
		chapterNavDisplay.setText(book.getChapter().getName());
		
		// Note! The initial Text Size was calculated on a 1024 x 600 pixel resolution (22px font).  This will scale to any device.
		pageNavDisplay.setTextSize(22 * (screenHeightInPixels/1024) * (screenWidthInPixels/600));
		chapterNavDisplay.setTextSize(22 * (screenHeightInPixels/1024) * (screenWidthInPixels/600));
		
		//System.out.println("book page name: " + book.getPageName());
		
		if(book.getPageName().contains("Quiz") || book.getPageName().contains("quiz"))
   	    {
	       	 if(bookNavToolView.getVisibility() == View.VISIBLE)
	       	 {
	       		 bookNavToolView.setVisibility(View.GONE);
	           	 progressView.setVisibility(View.INVISIBLE);
	           	 toolbarView.setVisibility(View.GONE);
	             hideBrightnessBar();
	       	 }
   	    }
		
		
		settings.setDefaultFontSize(currFontSize);
		//bookContent.setInitialScale(getScale());
	}//END turnPage
	
	/***************************************************************************************
	* This method will logically jump to a page.  This can be used to link from another
	* page.  The progress bar will be updated, and the correct page will be displayed. 
	* Bookmark status, and sticky notes will be correctly drawn.
	* 
	* @param page = Page to which the user is jumping
	**************************************************************************************/
	public void jumpToPage(Page page)
	{
		searchForString.resetSearchProgress();
		
		if(brightnessBar.getVisibility() == View.VISIBLE)
			hideBrightnessBar();
		
		/* Remove all sticky notes associated with the current page before turning */
		for(int stick = 0; stick < displayedStickies.size(); stick++)
		{
			absoluteBookLayout.removeView(displayedStickies.get(stick));
		}
		displayedStickies.clear();
		
		currentPageNum = page.getPageNum();
		
		
		if(currentPageNum == 1)										// First Page?
		{
			turnLeftButton.setClickable(false);
			turnLeftButton.setTextColor(Color.parseColor("Red"));	//Cannot go to Previous Page
			turnLeftButton.setVisibility(View.INVISIBLE);
			leftButtonIsClickable = false;
		}
		else if(currentPageNum == book.numPages())						// Last Page?
		{
			turnRightButton.setClickable(false);		
			turnRightButton.setTextColor(Color.parseColor("Red"));	// Cannot go to Next Page
			turnRightButton.setVisibility(View.INVISIBLE);
			rightButtonIsClickable = false;
		}
		else
		{
			turnRightButton.setClickable(true);
			turnRightButton.setTextColor(Color.parseColor("Black"));	//Re-enable Next Page button if disabled
			turnRightButton.setVisibility(View.VISIBLE);
			rightButtonIsClickable = true;
			
			turnLeftButton.setClickable(true);
			turnLeftButton.setTextColor(Color.parseColor("Black"));	//Re-enable Next Page button if disabled
			turnLeftButton.setVisibility(View.VISIBLE);
			leftButtonIsClickable = true;
		}
		
		bookContent.loadUrl(book.getPages().get((int)currentPageNum-1).getPageContent());	// Displays first Page
		book.setCurrentPage(book.getPages().get((int)currentPageNum-1));
		
		progBar.setProgress((int)currentPageNum-1);
		
		
		ArrayList<StickyNote> thisPageStickies = book.getCurrentPage().getAllStickyNotes();
		
		if(thisPageStickies.size() != 0)
		{
			/* Draw all sticky notes associated with the current page */
			for(int stick = 0; stick < thisPageStickies.size(); stick++)
			{
				ImageView stickyImage = new ImageView(this);
				stickyImage.setImageResource(R.drawable.sticky);
				
				AbsoluteLayout.LayoutParams imageLocation = new AbsoluteLayout.LayoutParams((int)(40 * bookContent.getScale()), (int)(40 * bookContent.getScale()), (int)thisPageStickies.get(stick).getXCoordinate(), (int)thisPageStickies.get(stick).getYCoordinate());
				
				stickyImage.setLayoutParams(imageLocation);
				stickyImage.setOnTouchListener((OnTouchListener) this);
				
				absoluteBookLayout.addView(stickyImage);
				displayedStickies.add(stickyImage);
			}
		}
		
		/* Change icon in bookmarkButton based on whether or not the current Page is bookmarked */
		if(book.getCurrentPage().isBookmarked())
			bookmarkButton.setImageResource(R.drawable.icon_bookmarked);
		else
			bookmarkButton.setImageResource(R.drawable.icon_bookmark_add);
		
		positionProgressToast();		
						
		pageNavDisplay.setText("" + book.getCurrentPage().getPageNum());
		chapterNavDisplay.setText(book.getChapter().getName());
		
		// Note! The initial Text Size was calculated on a 1024 x 600 pixel resolution (22px font).  This will scale to any device.
		pageNavDisplay.setTextSize(22 * (screenHeightInPixels/1024) * (screenWidthInPixels/600));
		chapterNavDisplay.setTextSize(22 * (screenHeightInPixels/1024) * (screenWidthInPixels/600));
		
	}//END jumpToPage
	
		
	/**
	*	Behavior triggered by a LongClick 
	*	1. Click on Page-turn buttons: Create new Thread to provide fast page-turning.
	**/
	public boolean onLongClick(View arg0)
	{
		System.out.println("LONG CLICK!");
		
		// 1.
		if(arg0.equals(turnLeftButton) || arg0.equals(turnRightButton))
		{
			longPressPageTurn = new Thread(this);
			longPressPageTurn.start();
			
	    	return false;	// Do not prevent regular touch events on the buttons from working
		}
		// 2.
		
		return false;
	}
	
	/** This is the method used to turn pages with a dragging motion of the user's finger.
	*  The method will identify where (x-coordinate) the screen was touched, and also where the finger
	*  was picked up.  If the up coordinate > down coordinate, Turn to next page, otherwise, Turn to previous page.
	*  
	*   This method also handles Sticky Note placement on the page.
	*/
	public boolean onTouch(View arg0, MotionEvent arg1) 
	{				
		/* Attaches a sticky note to the page where the user presses. */
		if(pendingSticky)
		{			
			if(arg1.getAction() == MotionEvent.ACTION_DOWN)
			{
				oneSticky.setCoordinates(arg1.getX(), arg1.getY());
				book.getCurrentPage().addStickyNoteToPage(oneSticky);
								
				ImageView stickyImage = new ImageView(this);
				stickyImage.setImageResource(R.drawable.sticky);
				
				
				@SuppressWarnings("deprecation")
				AbsoluteLayout.LayoutParams imageLocation = new AbsoluteLayout.LayoutParams((int)(40 * bookContent.getScale()), (int)(40 * bookContent.getScale()), (int)oneSticky.getXCoordinate(), (int)oneSticky.getYCoordinate());
				
				stickyImage.setLayoutParams(imageLocation);
				stickyImage.setVisibility(View.VISIBLE);
				
				absoluteBookLayout.addView(stickyImage);
				
				stickyImage.setOnTouchListener((OnTouchListener) this);
								
				displayedStickies.add(stickyImage);
				
				
				/* Only occurs when moving a sticky note.  Redraw all stickies. */
				if(stickyIsShowing)
				{
					stickyIsShowing = false;
					redrawStickyNotes(0, 0);
				}
			}
			else if(arg1.getAction() == MotionEvent.ACTION_UP)
			{
				pendingSticky = false;
				bookOverlay.setVisibility(View.GONE);
			}
		}

		else
		{
			// Get the action that was done on this touch event
			switch (arg1.getAction())
			{				
				case MotionEvent.ACTION_DOWN:
				{					
					/* Light up arrows */
					if(arg0.equals(turnLeftButton) || arg0.equals(turnRightButton) || arg0.equals(webBack) || arg0.equals(webForward))
					{
						startTime = System.currentTimeMillis();

						changeArrowButtons(1, arg0);
						
						if(arg0.equals(turnLeftButton) || arg0.equals(turnRightButton))
						{
							turnPage(arg0);
						}
																		
						return false;
					}
					if(arg0.equals(webRefresh))
					{
						arg0.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.reload_pressed));
						return true;
					}
					if(arg0.equals(webGo))
					{
						arg0.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.icon_browser_go_pressed));
						return true;
					}
					if(arg0.equals(notesButton))
					{
						notesButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_book_touch));
					}
					if(arg0.equals(sizeUpButton))
					{
						sizeUpButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_font_capital_touch));
					}
					if(arg0.equals(sizeDownButton))
					{
						sizeDownButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_font_regular_touch));
					}
					if(arg0.equals(searchButton))
					{
						searchButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_magnify_glass_touch));
					}
					if(arg0.equals(highlighterButton))
					{
						highlighterButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_highlight_touch));	
					}
					if(arg0.equals(tocButton))
					{
						tocButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_list_bullets_touch));	
					}
					if(arg0.equals(nightDayButton))
					{
						nightDayButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_contrast_touch));
						startTime = System.currentTimeMillis();
					}
					if(arg0.equals(stickyNotesButton))
					{
						stickyNotesButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_document_touch));
					}
					if(arg0.equals(toggleButton))
					{
						if(toolbarView.getVisibility() == View.GONE)
						{
							toggleButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_manage_touch));
						}
						else
						{
							toggleButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_manage_close_touch));						 
						}
					}
															
					StickyNote stickyHere = null;
					
					for(int s = 0; s < displayedStickies.size(); s++)
					{
						if(arg0.equals(displayedStickies.get(s)))
						{
							stickyHere = book.getCurrentPage().getAllStickyNotes().get(s);

							break;
						}
					}
										
					if(stickyHere != null)
					{
						stickyIsShowing = true;
						displayStickyContents(stickyHere);
												
						return false;
					}
					
					break;
				}
				case MotionEvent.ACTION_UP:
				{						
					/* Darken up arrows */
					if(arg0.equals(turnLeftButton) || arg0.equals(turnRightButton) || arg0.equals(webBack) || arg0.equals(webForward))
					{
						changeArrowButtons(0, arg0);
												
						if(arg0.equals(webBack) || arg0.equals(webForward))
						{
							externalBrowserClick(arg0);
						}
						
						System.out.println("No longer pressed");
						
						return true;
					}
					if(arg0.equals(webRefresh))
					{
						arg0.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.reload));
						externalBrowserClick(arg0);
						return true;
					}
					if(arg0.equals(webGo))
					{
						arg0.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.icon_browser_go));
						externalBrowserClick(arg0);
						return true;
					}
					if(arg0.equals(notesButton))
					{
						notesButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_book));
						myClick(notesButton);
					}
					if(arg0.equals(sizeUpButton))
					{
						sizeUpButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_font_capital));
						myClick(sizeUpButton);
					}
					if(arg0.equals(sizeDownButton))
					{
						sizeDownButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_font_regular));
						myClick(sizeDownButton);
					}
					if(arg0.equals(searchButton))
					{
						searchButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_magnify_glass));
						searchFunctions(searchButton);
					}
					if(arg0.equals(highlighterButton))
					{
						highlighterButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_highlight));	
						highlightText(highlighterButton);
					}
					if(arg0.equals(tocButton))
					{
						searchForString.resetSearchProgress();
						tocButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_list_bullets));	
						initializeTables(tocButton);
					}
					if(arg0.equals(nightDayButton))
					{
						endTime = System.currentTimeMillis();
						
						if(brightnessBarIsVisible)
							hideBrightnessBar();
						else
						{
							if(endTime - startTime > 500)
							{
								System.out.println("LONG PRESS");
								displayBrightnessBar();
							}
							else
							{
								toggleNightDay();
							}
						}
						
						nightDayButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_contrast));
						
					//	if(!brightnessBarIsVisible)
					//		toggleNightDay();
					}
					if(arg0.equals(stickyNotesButton))
					{
						stickyNotesButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_document));
						System.out.println("Changing Night/Day");
						attachStickyNote(stickyNotesButton);
					}
					if(arg0.equals(toggleButton))
					{
						if(toolbarView.getVisibility() == View.GONE)
						{
							toggleButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_manage));
							toggleToolbar(toggleButton);
						}
						else
						{
							toggleButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_manage_close));
							toggleToolbar(toggleButton);
						}
					}
					
					if(stickyIsShowing)
						return true;
					
					return true;
				}
			}
		}
		// if you return false, these actions will not be claimed by this listener
		return false;
	}//END onTouch
	
	/** This method will display the contents of a selected sticky note.  
	* User will be able to read Sticky Contents,
	* User will be able to move the StickyNote
	* User will be able to delete the StickyNote
	* @param stickyToDisplay
	*/
	public void displayStickyContents(StickyNote stickyToDisplay)
	{
		//If there is already a pending Sticky note, do not create a new one until the first is placed.
		pendingSticky = true;
		
		//oneSticky = new StickyNote();
		final StickyNote oneNote = stickyToDisplay;
		oneSticky = stickyToDisplay;
		stickyNote = new Dialog(this);
		LinearLayout stickyLayout = new LinearLayout(this);
		final EditText stickyText = new EditText(this);
		
		LinearLayout buttonLayout = new LinearLayout(this);
		Button saveButton = new Button(this);
		Button cancelButton = new Button(this);
		Button moveButton = new Button(this);
		Button deleteButton = new Button(this);
		
		LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
		buttonParams.setMargins(3, 3, 0, 3);
		LinearLayout.LayoutParams buttonParams2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
		buttonParams2.setMargins(0, 3, 3, 3);
		saveButton.setLayoutParams(buttonParams);
		cancelButton.setLayoutParams(buttonParams);
		moveButton.setLayoutParams(buttonParams);
		deleteButton.setLayoutParams(buttonParams2);
		
		/*
		|----------------------------|
		|     stickyNote	         |
		|----------------------------|
		|     stickyLayout    		 |
		|                     		 |
		|      stickyText     		 |
		|                     		 |
		|                     		 |
		|  ------------------------  |
		|     buttonLayout    		 |
		||Save||Cancel||Move||Delete||
		|----------------------------|
		*/
		
		stickyLayout.setOrientation(VERTICAL);
		stickyLayout.setBackgroundColor(Color.parseColor("#FFFFF68F"));
		
		buttonLayout.setOrientation(HORIZONTAL);
		buttonLayout.setBackgroundColor(Color.parseColor("#FFFFF68F"));
		
		stickyText.setBackgroundColor(Color.parseColor("#FFFFF68F"));
		stickyText.setTextColor(Color.parseColor("Black"));
		stickyText.setPadding(10,10,10,10);
		stickyText.setGravity(Gravity.TOP);
		stickyText.setText(stickyToDisplay.getText());
		
		if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
		{
			stickyText.setWidth(this.screenWidthInPixels / 2);
			stickyText.setHeight(this.screenHeightInPixels / 5);
		}
		else
		{
			stickyText.setWidth(globalView.getWidth() / 2);
			stickyText.setHeight(globalView.getHeight() / 3);
		}
		
		buttonLayout.addView(saveButton);
		buttonLayout.addView(cancelButton);
		buttonLayout.addView(moveButton);
		buttonLayout.addView(deleteButton);
		stickyLayout.addView(stickyText);
		stickyLayout.addView(buttonLayout);
		
		saveButton.setText("Save");
		saveButton.setTextColor(Color.parseColor("Black"));
		
		moveButton.setText("Move");
		moveButton.setTextColor(Color.parseColor("Black"));
		
		cancelButton.setText("Cancel");
		cancelButton.setTextColor(Color.parseColor("Black"));
		
		deleteButton.setText("Delete");
		deleteButton.setTextColor(Color.parseColor("Black"));
		
		/* Action that occurs when you click the Place button */
		moveButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) 
			{            	
				oneNote.setText(stickyText.getText());
				book.getCurrentPage().removeStickyNoteFromPage(oneNote);
				
				pendingSticky = true;
				bookOverlay.setVisibility(View.VISIBLE);
				//stickyIsShowing = false;
				
				stickyNote.cancel();
			}
		});
		
		/* Action that occurs when you click the Cancel button */
		cancelButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				stickyIsShowing = false;
				stickyNote.cancel();
			}
		});
		
		/* Action that occurs when you click the Delete button */
		deleteButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				book.getCurrentPage().removeStickyNoteFromPage(oneNote);
				redrawStickyNotes(0, 0);
				
				stickyIsShowing = false;
				stickyNote.cancel();
			}
		});
		
		/* Action that occurs when you click the Save button */
		saveButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				oneNote.setText(stickyText.getText());
				
				stickyIsShowing = false;
				stickyNote.cancel();
			}
		});
		
		stickyNote.setContentView(stickyLayout);
		stickyNote.show();
	}//END displayStickyContents
	
	/** When a sticky note is moved or deleted, the best way to handle the visual aspects is to remove
	*  all the images visible on the screen and then redraw the updated set of images.
	*/
	public void redrawStickyNotes(int xOffset, int yOffset)
	{
		/* Remove all sticky notes associated with the current page before turning */
		for(int stick = 0; stick < displayedStickies.size(); stick++)
		{
			absoluteBookLayout.removeView(displayedStickies.get(stick));
		}
		displayedStickies.clear();
		
		for(int stick = 0; stick < book.getCurrentPage().getAllStickyNotes().size(); stick++)
		{
			ImageView stickyImage = new ImageView(this);
			stickyImage.setImageResource(R.drawable.sticky);
			
			AbsoluteLayout.LayoutParams imageLocation = new AbsoluteLayout.LayoutParams((int)(40 * bookContent.getScale()), (int)(40 * bookContent.getScale()), (int)book.getCurrentPage().getAllStickyNotes().get(stick).getXCoordinate() + xOffset, (int)book.getCurrentPage().getAllStickyNotes().get(stick).getYCoordinate() + yOffset);
			
			stickyImage.setLayoutParams(imageLocation);
			stickyImage.setOnTouchListener((OnTouchListener) this);
			
			absoluteBookLayout.addView(stickyImage);
			
			displayedStickies.add(stickyImage);
		}		
	}//END redrawStickyNotes
	
	/** When a sticky note is moved or deleted, the best way to handle the visual aspects is to remove
	*  all the images visible on the screen and then redraw the updated set of images.
	*/
	public void redrawSingleStickyNote(int stickyIndex, int xOffset, int yOffset)
	{
		/* Remove this sticky note associated with the current page before turning */
		//absoluteBookLayout.removeView(displayedStickies.get(stickyIndex));
		ImageView stickyImage = displayedStickies.get(stickyIndex);
							
		AbsoluteLayout.LayoutParams imageLocation = new AbsoluteLayout.LayoutParams((int)(40 * bookContent.getScale()), (int)(40 * bookContent.getScale()), (int)book.getCurrentPage().getAllStickyNotes().get(stickyIndex).getXCoordinate() + xOffset, (int)book.getCurrentPage().getAllStickyNotes().get(stickyIndex).getYCoordinate() + yOffset);
			
		stickyImage.setLayoutParams(imageLocation);
		stickyImage.setOnTouchListener((OnTouchListener) this);
					
	}//END redrawSingleStickyNote
	
	/** Defines the behavior of the Activity when user closes the application window 
	*  - Notebook should commit its data to the external file.
	*  - Possibly track last book's current page.
	*/
	@Override
	public void onPause()
	{
		
		super.onPause();
		
	}
		
	/** Defines the behavior of the Activity when the Application is completely stopped. 
	*  - Notebook should commit its data to the external file.
	*  - Possibly track last book's current page.
	*/
	@Override
	public void onStop()
	{
		super.onStop();
		
		System.out.println("Stopping");
		
		
		FileOutputStream fileOut = null;
		ObjectOutputStream out;
		try {
			
			fileOut = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "/Books"));
			
			out = new ObjectOutputStream(fileOut);
			out.writeObject(Global.books);
			
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	
	public void searchFunctions(View button)
	{		
		if(button.equals(searchButton))
		{
			if(isSearchBarVisible == false)
			{
				searchForString.showSearchBar();
				
				isSearchBarVisible = true;
			}
			else
			{
				System.out.println("Search Button Pressed!");
				searchForString.doSearch(bookContent, searchButton);	
			}
		}
		else if(button.equals(closeButton))
		{
			searchForString.hideSearchBar(bookContent);
			
			isSearchBarVisible = false;
		}
		
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(searchBar.getWindowToken(), 0);
		
		if(brightnessBar.getVisibility() == View.VISIBLE)
			hideBrightnessBar();
	}
	
	public void changeArrowButtons(int change, View button)
	{
		if(change == 1)
		{
			if(button.equals(turnLeftButton))
			{
				button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.left_arrow_pressed));
				turnLeftButton.setPressed(true);
			}
			else if(button.equals(turnRightButton))
			{
				button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.right_arrow_pressed));
				turnRightButton.setPressed(true);
			}
			else if(button.equals(webBack))
			{
				button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.left_arrow_web_enabled_pressed));
			}
			else if(button.equals(webForward))
			{
				button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.right_arrow_web_enabled_pressed));
			}
			
		}
		else
		{
			if(button.equals(turnLeftButton))
			{
				button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.left_arrow));
				turnLeftButton.setPressed(false);
			}
			else if(button.equals(turnRightButton))
			{
				button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.right_arrow));
				turnRightButton.setPressed(false);
			}
			else if(button.equals(webBack))
				button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.left_arrow_web_enabled));
			else if(button.equals(webForward))
				button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.right_arrow_web_enabled));
			
			
		}
		
	}
	
	/**
	* This Method is responsible for displaying Images on an isolated screen where a user can interact with them.
	* In all comments below this Logical display area for images will be referred to as the Image Viewer.
	* User can Zoom into the image, pan around, and double-tap to return it to its original size.
	*  
	* @param imageName = String name of the image in this book to be displayed in the viewer
	* @throws IOException
	*/
	public void displayImageFullScreen(String imageName) throws IOException
	{    	
		displayingImageFullScreen = true;		//Determines if the image viewer should be displayed on orientation change 
		imageOnDisplay = imageName;				//Made global in case Orientation is changed
		
		System.out.println("Image to show = " + imageName);
		String imagePath = "file:///" + Environment.getExternalStorageDirectory() + "/Textbooks/" + book.getBookTitle() + "/res/" + imageName;  //Dynamically find correct image in this book!
		System.out.println(imagePath);
		ArrayList<Figure> allImages = book.getChapter().getAllFigures();
		
		setContentView(R.xml.full_image);		//Display Image Viewer
		
		WebView imageViewer = (WebView) findViewById(R.id.imageDisplay);
		TextView figureCaption = (TextView)findViewById(R.id.imageCaption);
			
		for(int i = 0; i < allImages.size(); i++)
		{
			Figure thisFig = allImages.get(i);
						
			if(thisFig.getFigureName().equals(imageName))
			{
				figureCaption.setText("Fig " + book.getChapter().getId() + "." + thisFig.getFigureNumber() + ": " + thisFig.getFigureCaption());
				System.out.println("FIGURE CAPTION: Fig " + book.getChapter().getId() + "." + thisFig.getFigureNumber() + ": " + thisFig.getFigureCaption());
				break;
			}
		}
		
		
		String html = new String();
		html = ("<html><head><title></title><style type=\"text/css\">table{width:100%; height:100%;}td{height:100%;vertical-align:center;}</style></head><body><table><tr><td><center><img src=\""+imagePath+"\"></center></td></tr></table></body></html>");	
		imageViewer.getSettings().setSupportZoom(true);			   //Enables Zoom
		imageViewer.getSettings().setBuiltInZoomControls(true);    //Enable Multitouch
		imageViewer.getSettings().setUseWideViewPort(true);		   //Double-Tap
		imageViewer.setInitialScale(1);//Fit content to screen
		//imageViewer.getZoomControls().setVisibility(View.GONE);	// No longer supported by Android -- getZoomControls returns null.
		imageViewer.loadDataWithBaseURL(imagePath,html,"text/html","utf-8","");		
	}
	
	/**
	* Goes back to correct page in book when the user has finished with the Image Viewer.
	* @param button
	*/
	public void backToTextFromImage(View button)
	{
		displayingImageFullScreen = false;
		setContentView(R.layout.main);
				
		this.onConfigurationChanged(null);		//Redisplays all current information on book screen rather than ImageViewer screen
		
		while(!okayToAnchor)
		{
			//System.out.println("Should load: " + book.getCurrentPage().getPageContent() + "#" + imageOnDisplay);
			bookContent.loadUrl(book.getCurrentPage().getPageContent() + "#" + imageOnDisplay);
		}
		bookContent.loadUrl(book.getCurrentPage().getPageContent() + "#" + imageOnDisplay);
		//System.out.println("Book Loaded: " + book.getCurrentPage().getPageContent() + "#" + imageOnDisplay);
	}
	
		
	/**
	* What happens when the user presses on of the built-in buttons
	*/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) 
	{
		switch(keyCode)
		{
			case KeyEvent.KEYCODE_BACK:
			{
				if(displayingImageFullScreen)
					backToTextFromImage(findViewById(R.id.backButton));
				else if(displayingExternalPage)
					backToTextFromWeb(findViewById(R.id.webBackButton));
				else
					return(super.onKeyDown(keyCode, event));		//Default Behavior
				
				break;
			}
			case KeyEvent.KEYCODE_SEARCH:
			{
				if(!displayingExternalPage)
				{				
					if(isSearchBarVisible == false)
					{
						searchFunctions(closeButton);
						
						searchFunctions(searchButton);
					}
					else if(isSearchBarVisible == true && searchBar.getText().toString().equals(""))
					{
						searchFunctions(closeButton);
					}
					else if(isSearchBarVisible == true)
					{
						searchFunctions(searchButton);
					}
				}
			}
			case KeyEvent.KEYCODE_ENTER:
			{
				if(displayingExternalPage)
					externalBrowserClick(findViewById(R.id.webGoButton));
			}
		}
		
		if(brightnessBar.getVisibility() == View.VISIBLE)
			hideBrightnessBar();
		
		return true;
	}
	
	
	
	public void playVid()
	{
		setContentView(R.xml.full_video);		//Display Image Viewer
		
		SurfaceView vidSurface = (SurfaceView) findViewById(R.id.videoSurface);
		SurfaceHolder vidHolder = vidSurface.getHolder();		
		MediaPlayer player = MediaPlayer.create(this, R.raw.video);
		
		vidHolder.addCallback(this);
		vidHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		vidHolder.setFixedSize(getWindow().getWindowManager().getDefaultDisplay().getWidth(), getWindow().getWindowManager().getDefaultDisplay().getHeight());
		vidHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		
		player.setDisplay(vidHolder);
		
		player.setAudioStreamType(AudioManager.STREAM_MUSIC);
		
		try {
		player.prepare();
		} catch (Exception e) {
		e.printStackTrace();
		}
		player.start();
		
		
		
		/*setContentView(R.xml.full_video);		//Display Image Viewer
		
		VideoView vidViewer = (VideoView)findViewById(R.id.videoDisplay);
		vidViewer.canPause();
		vidViewer.canSeekBackward();
		vidViewer.canSeekForward();
		//vidViewer.stopPlayback();
		//vidViewer.pause();
		//vidViewer.resume();
		//vidViewer.start();
		//vidViewer.seekTo();
		vidViewer.setVideoPath("file:///android_asset/video.mp4");
		*/
		/*		try {
		mp.prepare();
		} catch (IllegalStateException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}
		mp.start();
		*/	
	}
	
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
	int height) {
	// TODO Auto-generated method stub
	
	}
	
	public void surfaceCreated(SurfaceHolder holder) {
	// TODO Auto-generated method stub
		playVid();
	}
	
	public void surfaceDestroyed(SurfaceHolder holder) {
	// TODO Auto-generated method stub
	
	}
	

	public void redrawAllStickiesScaled(float oldScale, float newScale)
	{	
		float scaleRatio = newScale/oldScale;
		/* Remove all sticky notes associated with the current page before turning */
		for(int stick = 0; stick < displayedStickies.size(); stick++)
		{
			absoluteBookLayout.removeView(displayedStickies.get(stick));
		}
		displayedStickies.clear();
		
		for(int stick = 0; stick < book.getCurrentPage().getAllStickyNotes().size(); stick++)
		{
			ImageView stickyImage = new ImageView(this);
			stickyImage.setImageResource(R.drawable.sticky);
			
			AbsoluteLayout.LayoutParams imageLocation = new AbsoluteLayout.LayoutParams((int)(40*scaleRatio), (int)(40*scaleRatio), (int)(book.getCurrentPage().getAllStickyNotes().get(stick).getXCoordinate() * scaleRatio), (int)(book.getCurrentPage().getAllStickyNotes().get(stick).getYCoordinate() * scaleRatio));
			
			stickyImage.setLayoutParams(imageLocation);
			stickyImage.setOnTouchListener((OnTouchListener) this);
			
			absoluteBookLayout.addView(stickyImage);
			
			displayedStickies.add(stickyImage);
		}

	}
	
	/**
	* This Method is responsible for displaying External Web Pages on an isolated screen where a user can interact with them.
	* In all comments below this Logical display area for external Web Pages will be referred to as the Web Viewer.
	* User can Zoom into the Page, pan around, and double-tap to return it to its original size, just like book pages.
	*  
	* @param webURL = URL of WebPage to be displayed in the viewer
	* @throws IOException
	*/
	public void displayExternalWebPage(String webAddress) throws IOException
	{   
		displayingExternalPage = true;
		
		setContentView(R.xml.external_web);		//Display Web Viewer
		
		addressBar = (EditText)findViewById(R.id.webAddressBar);
		browser = (WebView) findViewById(R.id.externalWebDisplay);
		webForward = (Button)findViewById(R.id.webForwardButton);
		webBack = (Button)findViewById(R.id.webBackButton);
		webRefresh = (Button)findViewById(R.id.webReloadButton);
		webGo = (Button)findViewById(R.id.webGoButton);
		webLoading = (ProgressBar)findViewById(R.id.webProgressBar);
		webLoading.setProgressDrawable(getResources().getDrawable(R.drawable.red_progress));
					
		browser.setWebViewClient(new MyWebViewClient());
		browser.getSettings().setJavaScriptEnabled(true);
		browser.getSettings().setSupportZoom(true);			   //Enables Zoom
		browser.getSettings().setBuiltInZoomControls(true);    //Enable Multitouch
		browser.getSettings().setUseWideViewPort(true);		   //Double-Tap
		browser.getSettings().setLoadWithOverviewMode(true);
		browser.getZoomControls().setVisibility(View.GONE);
		
		if(isOnline())
		{
			browser.loadUrl(webAddress);
		}
		else
		{
			String connectionMessage = "We are unable to load the requested page because we cannot establish an Internet connection!  Please ensure that you have Internet access and try again!";
			String html = new String();
			html = ("<html><head><title></title></head><body><h1><center>"+connectionMessage+"</center></h1></body></html>");
			browser.loadDataWithBaseURL(connectionMessage,html,"text/html","utf-8","");
			
			webForward.setClickable(false);
			webForward.setEnabled(false);
			webBack.setClickable(false);
			webBack.setEnabled(false);
			webGo.setClickable(false);
			webGo.setEnabled(false);
			webRefresh.setClickable(false);
			webRefresh.setEnabled(false);
			
			addressBar.setText("Connectivity Error");
		}
						
		webForward.setOnTouchListener((OnTouchListener) this);
		webBack.setOnTouchListener((OnTouchListener) this);
		webRefresh.setOnTouchListener((OnTouchListener) this);
		webGo.setOnTouchListener((OnTouchListener) this);
		
		resetWebButtons(webForward, webBack, webRefresh);
	}
	
	public void externalBrowserClick(View button)
	{	
		webForward = (Button)findViewById(R.id.webForwardButton);
		webBack = (Button)findViewById(R.id.webBackButton);
		webRefresh = (Button)findViewById(R.id.webReloadButton);
		webGo = (Button)findViewById(R.id.webGoButton);
		
		webForward.setOnTouchListener((OnTouchListener) this);
		webBack.setOnTouchListener((OnTouchListener) this);
		webRefresh.setOnTouchListener((OnTouchListener) this);
		webGo.setOnTouchListener((OnTouchListener) this);
		
		
		if(button.equals(webForward))
		{
			if(browser.canGoForward())
				browser.goForward();
		}
		else if(button.equals(webBack))
		{
			if(browser.canGoBack())
				browser.goBack();
		}
		else if(button.equals(webRefresh))
		{		
			browser.reload();
		}
		else if(button.equals(webGo))
		{
			String newPage = addressBar.getText().toString();
			
			if(!newPage.equals(browser.getUrl()))
			{
				if(newPage.substring(0,11).equals("http://www."))
					browser.loadUrl(newPage);
				else if(newPage.substring(0,7).equals("http://"))
					browser.loadUrl("www." + newPage);
				else
					browser.loadUrl("http://www." + newPage);
			}
			
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(addressBar.getWindowToken(), 0);
			
		}
		
		resetWebButtons(webForward, webBack, webRefresh);
	}
	
	public void resetWebButtons(Button webForward, Button webBack, Button webRefresh)
	{		
		if(browser.canGoForward())
		{
			webForward.setBackgroundResource(R.drawable.right_arrow_web_enabled);
			webForward.setClickable(true);
			webForward.setEnabled(true);
		}
		else
		{
			webForward.setBackgroundResource(R.drawable.right_arrow);
			webForward.setClickable(false);
			webForward.setEnabled(false);
		}
		
		if(browser.canGoBack())
		{
			webBack.setBackgroundResource(R.drawable.left_arrow_web_enabled);
			webBack.setClickable(true);
			webBack.setEnabled(true);
		}
		else
		{
			webBack.setBackgroundResource(R.drawable.left_arrow);
			webBack.setClickable(false);
			webBack.setEnabled(false);
		}
	}
	
	/**
	* Goes back to correct page in book when the user has finished with the External Web Page Viewer.
	* @param button
	*/
	public void backToTextFromWeb(View button)
	{
		displayingExternalPage = false;

		setContentView(R.layout.main);
				
		this.onConfigurationChanged(null);		//Redisplays all current information on book screen rather than ImageViewer screen
	}
	
	/** Method to determine whether or not the device is connected to the Internet **/
	public boolean isOnline() 
	{
		 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		 
		 if(cm.getActiveNetworkInfo() == null)
		 {
			 return false;
		 }
		 else
		 {
			 return cm.getActiveNetworkInfo().isConnected();
		 }
	}
	
	/** This method aligns and scales the Page Progress Toast properly **/
	public void positionProgressToast()
	{
		/* Set the Progress Toast information */
		// Note: These settings center the Progress Toast based on absolute values on a 600 x 1024 display
		if(toolbarView.getVisibility() == View.GONE)
			toastOffsetX = 0;
		else
			toastOffsetX = toolbarView.getRight() - (52 * screenWidthInPixels/600);		// Center of Progress Bar Horizontally
		
		if(progressView.getTop() != 0)
			toastOffsetY = progressView.getTop() - screenHeightInPixels/2 - (20 * screenHeightInPixels/1024); // Slightly above Progress Bar
		else
			toastOffsetY =  (928 * screenHeightInPixels/1024) - screenHeightInPixels/2 - (20 * screenHeightInPixels/1024); // Slightly above Progress Bar
		
		pageProg.setGravity(Gravity.CENTER, toastOffsetX, toastOffsetY);	//Set these values and position the Toast.
		
		
		LinearLayout toastLayout = new LinearLayout(this);
		toastLayout.setBackgroundColor(Color.parseColor("#99B80000"));
		TextView toastText = new TextView(this);							//Holds Text for Toast
		toastText.setBackgroundColor(Color.parseColor("#99B80000"));
		toastText.setText("Page " + currentPageNum + " / " + book.numPages());
		toastText.setTextColor(Color.parseColor("#FFFFFFFF"));
		toastText.setTextSize(20 * ((screenHeightInPixels/1024) * (screenWidthInPixels/600)));
		toastText.setPadding(5, 5, 5, 5);
		toastLayout.addView(toastText);
	
		pageProg.setView(toastLayout);

		pageProg.show();
		/**/
	}
	
	/** This method will initialize the Tables Activity which should display the Table of Contents, Figures, etc. **/
	public void initializeTables(View button)
	{		
		if(shouldShowGlossary == false)
		{		
			String termToShow = "";
			
			//bun = getIntent().getExtras();
			
			//Bundle bun = new Bundle();
			//bun.putSerializable("Book", this.book);
			bun.putInt("bookIndex", book.getBookID());
			bun.putSerializable("Glossary", null);
			bun.putSerializable("ShowGloss", shouldShowGlossary);
		}
		
		Intent tableIntent = new Intent(button.getContext(), Tables.class);
    	tableIntent.putExtras(bun);
    	
        startActivityForResult(tableIntent, 0);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
		Intent i = data;
		if(i != null)
		{
			Page p = (Page)data.getExtras().get("Page");
			String urlToLoad;
			
			jumpToPage(p);
			
			if(data.hasExtra("Anchor"))
			{
				urlToLoad = (String)data.getExtras().get("Anchor");
				System.out.println("Should load: " + urlToLoad);
				
				while(!okayToAnchor)
				{
					System.out.println("Attempting to load: " + urlToLoad);
				}
				
				if(okayToAnchor)
				{
					bookContent.loadUrl(urlToLoad);
					redrawStickyNotes(0, 0);
				}
				
				System.out.println(bookContent.getOriginalUrl());
				System.out.println(bookContent.getUrl());
			}
		}
		else
		{
			System.out.println("Returning Null from Gloss");
		}
		
		shouldShowGlossary = false;
    }
	
	public void addNotebookTab()
	{
		TextView newtab = new TextView(main);  //Tab label to add		
		
		LinearLayout.LayoutParams layoutP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		layoutP.setMargins(3,0,0,0);
		newtab.setLayoutParams(layoutP);
		newtab.setText("Notes " + (theNotebook.getNumNotebookPages()+1));
		newtab.setBackgroundColor(Color.parseColor("#FFCC0000"));
		newtab.setTextColor(Color.parseColor("#FFFFFFFF"));
		newtab.setTextSize(18);
		newtab.setMinimumWidth(20);
		newtab.setPadding(10,5,10,5);
		
		/* Create Logical Notebook Page for this new Tab */
		NotebookPage newPage = new NotebookPage();
		newPage.setColor(Color.parseColor("#FF980000"));
		newPage.setTabLabel(newtab.getText().toString());
		theNotebook.addNewNBPage(newPage);
		
		/* Make all old tabs "deselected" */
		for(int tab = 0; tab < allNBTabs.size(); tab++)
		{
			allNBTabs.get(tab).setBackgroundColor(Color.parseColor("#FF980000"));
			allNBTabs.get(tab).setTextColor(Color.parseColor("#FFCCCCCC"));
			allNBTabs.get(tab).setTextSize(14);
			allNBTabs.get(tab).setMinimumWidth(10);
		}
		
		/* Save current notes to current Notebook page */
		currentNBPage.setTextOnPage(notesContent.getText());

		/* Create new blank page */
		notesContent.setText("");				 
		notebookTabTouch.initializeTabSettings(newtab);
				
		currentTab = newtab;
		currentTabNum = allNBTabs.size();
									
		tabLayout2.addView(newtab);
		allNBTabs.add(newtab);
		numberOfTabs++;
		
		currentNBPage = theNotebook.getNBPage(theNotebook.getNumNotebookPages()-1);
	}
	
	public int getDensityPixels(int pixels)
	{	
		float d = this.getResources().getDisplayMetrics().density;
		
		int densityPix = (int)(pixels * d);
		
		return densityPix;
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent e){
	    super.dispatchTouchEvent(e);
	    //return mGestureDetector.onTouchEvent(e);
	    return true;
	}

	/**
	* Parallel Thread for managing long-presses on page-turn buttons.
	**/
	public void run() 
	{
		if(Thread.currentThread().equals(flinger))
		{
			flingStickies();
		}
		System.out.println("Starting the Long-press Thread!");
		
		try
		{
			Thread.sleep(500);
			
			while(true)
			{
				Thread.sleep(100);
				
				if(turnLeftButton.isPressed())
				{
					System.out.println("TURN LEFT!");
					
					runOnUiThread(new Runnable() 
					{
					    public void run() {
					        main.turnPage(turnLeftButton);
					    }
					});

					
					//main.turnPage(turnLeftButton);						
				}
				else if(turnRightButton.isPressed())
				{
					System.out.println("TURN RIGHT!");
					runOnUiThread(new Runnable() 
					{
					    public void run() {
					        main.turnPage(turnRightButton);
					    }
					});
				}
				else
				{
					break;
				}
			}
			
			return;
		}
		catch(Exception e){}
		
	}
	
	public void hideBrightnessBar()
	{
		brightnessBar.setVisibility(View.GONE);
		brightnessBarIsVisible = false;
	}
	
	public void displayBrightnessBar()
	{
		int buttonCoords[] = new int[2];
		nightDayButton.getLocationOnScreen(buttonCoords);
		int toolbarWidth = this.toolbarView.getWidth();
		float buttonHeight = nightDayButton.getHeight();
	   	
		@SuppressWarnings("deprecation")
		AbsoluteLayout.LayoutParams brightnessBarParams = new AbsoluteLayout.LayoutParams(256, (int)buttonHeight, toolbarWidth + 5, (int)(buttonCoords[1]));
		brightnessBar.setLayoutParams(brightnessBarParams);
	    	
		try 
		{
			float currentBrightness = android.provider.Settings.System.getInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS);
					
			brightnessBar.setMax(255);
			brightnessBar.setProgress((int)(currentBrightness));
			brightnessBar.setVisibility(View.VISIBLE);
			brightnessBarIsVisible = true;
		} 
		catch (SettingNotFoundException e) 
		{
			e.printStackTrace();
		}
	}
	
	/* Redraws sticky notes when a flinging gesture occurs */
	public void flingStickies()
	{
		System.out.println("FLING STICKY NOTES!");
		
		lastXScroll = bookContent.getScrollX();
		lastYScroll = bookContent.getScrollY();
		
		try
		{
			while(true)
			{
				Thread.sleep(50);
			
				currXScroll = bookContent.getScrollX();
				currYScroll = bookContent.getScrollY();
				
				if(currXScroll != lastXScroll || currYScroll != lastYScroll)
				{
					System.out.println("Still Flinging");
					
					if(book.getCurrentPage().hasStickyNotes())
	    			 {
	    				 ArrayList<StickyNote> allStickies = book.getCurrentPage().getAllStickyNotes();
	    				 for(int s = 0; s < allStickies.size(); s++)
	    				 {
	    					 StickyNote sNote = allStickies.get(s);
	    				 
	    					 sNote.setCoordinates((float)((sNote.getXCoordinate() + lastXScroll - currXScroll)), (float)((sNote.getYCoordinate() + lastYScroll - currYScroll)));
	    				 }
	    				 
	    				 runOnUiThread(new Runnable() 
	 					 {
	 					    public void run() 
	 					    {
	 					    	redrawStickyNotes(main.currXScroll - main.lastXScroll, main.currYScroll - main.lastYScroll);
	 					    }
	 					 });
	    			 }
				}
				else
				{
					System.out.println("Done Flinging");
					break;
				}
				
				lastXScroll = currXScroll;
				lastYScroll = currYScroll;
			}
		}
		catch(Exception e){ e.printStackTrace(); }
	}

}